我很困惑为什么以下两个for循环场景生成不同的输出,从相同的行列表开始:
print lines
['175.11\n', '176.39\t56.887\n', '178.17\n', '176.1\t51.679\n', '176.1\t51.679\n', '175.15\n', '176.91\t32.149\t30.344\n', '182.33\n', '173.04\n', '174.31\n']
情景#1:括号内循环
当我运行以下内容时:
lines = ["Total = "+line for line in lines]
print lines
行变为:
['Total = 175.11\n', 'Total = 176.39\t56.887\n', 'Total = 178.17\n', 'Total = 176.1\t51.679\n', 'Total = 176.1\t51.679\n', 'Total = 175.15\n', 'Total = 176.91\t32.149\t30.344\n', 'Total = 182.33\n', 'Total = 173.04\n', 'Total = 174.31\n']
情景#2:未加括号的for-loop
但是,当我运行时:
for line in lines:
lines = ["Total = "+line]
print lines
行只变为:
['Total = 174.31\n']
我非常感谢任何帮助解释这里发生了什么! (另外,我应该提一下,我对SCENARIO#1的输出更感兴趣,但希望使用SCENARIO#2的格式来实现它。
答案 0 :(得分:3)
您正在覆盖每个循环迭代的列表,而不是附加到它。
修复将是:
myList = []
for line in lines:
myList.append("Total = " + line) # appends the r-value to your list
但无论如何,我仍然更喜欢列表理解的简洁性。
您还可以使用条件列表理解:
# excludes empty lines
myList = ["Total = "+line for line in lines if len(line) > 0]
您正在修改正在迭代的列表
当您的for循环进展到lines
时,您正在追加新项目。每当您修改容器时,您正在迭代结果可能会造成损害。 Read this question