-1

谁能解释一下?

userData = 10
emptyList = [0] * userData
for i in emptyList: 
    emptyList[i] = userData
    print(emptyList)
    userData -= 1

在我看来,这段代码应该做一些不同的事情。

我在寻找什么 - 无论 userData 的值是什么,我都希望它在列表 emptyList 中按顺序值进行索引。

这个,我想会给我集合 [10, 9, 8] 等等......它没有......它只改变每次迭代中的第一个变量

我做错了什么?

我让它以另一种方式工作,userData = 10 emptyList = [] for i in range(userData): emptyList.append(i) userData -= 1 print(emptyList)

但这不是我喜欢的方式..我认为那组中的 0 需要输出为 10

4

5 回答 5

2
userData = 10
emptyList = [0] * userData
print emptyList

will print

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

and in the loop,

for i in emptyList:
    print i,

will print

0 0 0 0 0 0 0 0 0 0

So, in all the iterations of the loop, you are changing just the first element of the list. What you should actually have done is

userData = 10
emptyList = [0] * userData

for i in range(len(emptyList)):
    emptyList[i] = userData
    userData -= 1
print emptyList

Output

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

There is a builtin function called range which accepts starting value, ending value and the increment value and generates a sequence of values. With that function you can do this in a single line

print range(10, 0, -1)  #Python 2
print list(range(10, 0, -1))  #Python 3
于 2013-11-15T03:29:25.213 回答
0

该行:

for i in emptyList:

会给你一个循环,依次设置i每个值。emptyList

由于所有这些值都为零,这意味着i将始终为零,因此它只会更改第一个值。

如果你想要 list [10,9,8,7,6,5,4,3,2,1],只需使用更多 Pythonic :

emptylist = [x for x in range (10, 0, -1)]
于 2013-11-15T03:31:03.773 回答
0

也许你正在阅读这样的代码

userData = 10
emptyList = [0] * userData
for i in range(len(emptyList)): # note range and len here
    emptyList[i] = userData
    print(emptyList)
    userData -= 1

你可以使用

emptyList = range(userData, 0, -1)

还是应该做更多的事情?

于 2013-11-15T03:31:50.363 回答
0

Python 中的for循环与其他语言有着根本的不同——它更像是一个 for each循环(也就是说,对于可迭代对象中的每个元素,用它来做事)。

如果要创建元素列表,请使用xrangePython 2.x 或rangePython 3.x:

emptyList = [i for i in xrange(10, 0, -1)]

emptyList = [i for i in range(10, 0, -1)]
于 2013-11-15T03:32:04.617 回答
0

你想要类似的东西

for i, j in emptyList:
  emptyList[j] = userData
  userData -= 1

现在你得到了 value i(你不关心)和 index j,这是你需要的。

请参阅在 Python 'for' 循环中访问索引- 您不是第一个在 Python 中为循环而苦苦挣扎的人!

于 2013-11-15T03:32:17.670 回答