这是我的第一个问题,如果需要重新命名或移到另一个部分,我很抱歉。
我正在尝试编写一个循环,将数字 1-4 append 到 list1 中的每个字符串,并将这些新字符串放入 list2 中。这是我目前所做的:
number = 0
list1 = ["a","b","c"]
list2=[]
for item in list1:
while number < 5:
list2.append(str(item)+str(number))
number = number + 1
我不知道下一步该做什么。任何帮助,将不胜感激。
附言现在,如果我这样做 打印 list 2 它输出 ['a0', 'a1', 'a2', 'a3', 'a4']。我想要发生的是
print list2
['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4']
请您参考如下方法:
问题是您在 for 循环之外初始化了 number。因此,即使 for 对 list1 中的所有项目执行,while 也不会对后续项目执行,因为条件为 false .
list1 = ["a","b","c"]
list2=[]
for item in list1:
number = 1 # You need to reset number within the loop, not outside!
while number < 5:
list2.append(str(item)+str(number))
number = number + 1
print list2
产生:
['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4']
