如何在python中遍历列表列表

时间:2019-08-06 18:25:29

标签: python loops nested

需要遍历列表列表并测试字符串是黑色还是红色,然后从列表的浮点数中添加或减去-例如,如果“ Black”为1,则为1,如果字符串值为“ Red”,则为1。 / p>

new_line = [["Black", 3.0], ["Red", 7.0], ["Red", 2.0], ["Black", 3.5]]

for i in new line:
    if value == "Black":
          add =+ 1 to float value (3.0 in first example)
    else: 
          subtract -=1 float value (7.0 in second value n list)

3 个答案:

答案 0 :(得分:1)

您非常接近。应该这样做:

new_line = [["Black", 3.0], ["Red", 7.0], ["Red", 2.0], ["Black", 3.5]]

for i in new_line:
    if i[0] == "Black":
          i[1] += 1
    else: 
          i[1] -=1

答案 1 :(得分:1)

这应该有效

new_line = [["Black", 3.0], ["Red", 7.0], ["Red", 2.0], ["Black", 3.5]]

for i in new_line:
     if i[0] == "Black":
          i[1] += 1.0
     else: 
          i[1] -= 1.0

 print(new_line)

答案 2 :(得分:0)

您还可以使用列表理解:

new_line = [[color,value+(color=="Black")*2-1] for color,value in new_line]