[英]How I can update a list of lists in python?
I have a list of lists and I want to make modifications on the lists strings.我有一个列表列表,我想对列表字符串进行修改。
m_list = [['D-1', 'D-2', 'D-3'],
['J-3', 'J-4', 'J-5', 'J-6'],
['R-1', 'R-2', 'R-3'],
['U-1', 'U-2', 'U-3', 'U-4']]
I want to change "-" with "00", this is my try:我想用“00”改变“-”,这是我的尝试:
for m in m_list:
for turbine in m:
turbine = turbine.replace("-", "00")
print(turbine)
print(m)
I miss the part of replacing the lists.我错过了替换列表的部分。
This is the result I want:这是我想要的结果:
m_list = [['D001', 'D002', 'D003'],
['J003', 'J004', 'J005', 'J006'],
['R001', 'R002', 'R003'],
['U001', 'U002', 'U003', 'U004']]
Try using list comprehension:尝试使用列表理解:
print([[x.replace('-', '00') for x in i] for i in m_list])
Or add a map
:或添加
map
:
print([list(map(lambda x: x.replace('-', '00'), i)) for i in m_list])
Or add two map
s:或者添加两个
map
:
print(list(map(lambda i: list(map(lambda x: x.replace('-', '00'), i)), m_list)))
Of course, the nested list comprehension is the best.当然,嵌套列表理解是最好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.