简体   繁体   中英

Replacing string with tuple in list of tuples

I am very sorry to be asking this kind of newbie question but here it goes. So I basically have this returned as levels:

levels = [(1, 210, 30, 500, 500, 'white'),(1, 210, 30, 200, 400, 'white'),(1, 210, 30, 600, 300, 'white')]

And I want to iterate through it and replace 'white' with white which is simply (255,255,255). Python complained about tuples not being changeable, so I would need to create a new list with the tuples instead of white. Is there a quick way to do this?

just do

levelsList = [list(x) for x in level]

After that you can change the 'white' string

If you want to keep it as a list of tuples, you can try:

replacements = {"white": (255, 255, 255)}
levelsList = [(a, b, c, d, e, replacements.get(f, f)) for a, b, c, d, e, f in levels]

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