简体   繁体   English

循环列表中的列表

[英]Looping over lists in list

I have two lists with numbers. 我有两个带数字的列表。

newlist      = [506.5, 133.0, 11104.2]
totalcolumns = [9.2, 10024.5, 610.0, 1100.0]

I want to loop over both lists and format the numbers in the same way: 我想循环遍历两个列表并以相同的方式格式化数字:

myformatlists = [newlist, totalcolumns]

for i in range(0,len(myformatlists)):
     myformatlists[i] = ['{0:,}'.format(x) for x in myformatlists[i]]
     myformatlists[i] = [regex.sub("\.0?$", "", x).replace(".", "_").replace(",", ".")

printing 印花

print(str(myformatlists[i]) 

gives the correct new values 给出正确的新值

but

print(str(newlist))
print(str(totalcolumns))

still gives the old lists. 仍然给出旧列表。
Why doesn't my for-loop assign the values to the listname in myformatlists[i]? 为什么我的for循环没有将值分配给myformatlists [i]中的listname?

How can I assign the output of the for-loop to the list in myformatlists? 如何将for-loop的输出分配给myformatlists中的列表?

myformatlists[i] = ['{0:,}'.format(x) for x in myformatlists[i]]

rebinds myformatlists[i] , it does not alter the original item of myformatlists . 重新绑定myformatlists[i] ,它不会改变myformatlists的原始项目。

You can perform an inplace update of myformatlists[i] using slice notation: 您可以使用切片表示法执行myformatlists[i]的就地更新:

myformatlists[i][:] = ['{0:,}'.format(x) for x in myformatlists[i]]

This will mutate the original list. 这将改变原始列表。

But note that there is a problem with the re code where x is not defined becaue the list comprehension is incomplete: 但请注意,由于列表理解不完整,重新编码中存在x未定义的问题:

myformatlists[i] = [regex.sub("\.0?$", "", x).replace(".", "_").replace(",", ".")

It should be re.sub and perhaps the rest should be: 它应该是re.sub ,其余应该是:

myformatlists[i] = [re.sub("\.0?$", "", x).replace(".", "_").replace(",", ".") for x in myformatlists[i]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM