简体   繁体   中英

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:

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 :

print([list(map(lambda x: x.replace('-', '00'), i)) for i in m_list])

Or add two map s:

print(list(map(lambda i: list(map(lambda x: x.replace('-', '00'), i)), m_list)))

Of course, the nested list comprehension is the best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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