更新与 python 中的键匹配的子列表的值?
Update the value of sublist where match the key in python?
考虑以下嵌套列表:
nested_list = [[1, "adam", 20],
[2, "lucy", 40],
[3, "mary", 50]]
我想做以下条件举例:
搜索 '3' 关键字,如果找到则检查第二个元素是否为“mary”,然后更新第三个元素。
伪:
if '3' is found in nested_list then
if index[1] == "mary" then
index[2] = 50 + 10 (update)
你在伪代码上有一个位置,我们可以直接改成代码。你有基本的想法,遍历 nested_list
检查任何列表中的第一个元素是否等于 3
。然后我们需要检查第二个索引,看它是否等于 mary
。如果两个测试都通过,我们需要更新列表中的最后一个元素。
代码
nested_list = [[1,"adam", 20],[2, "lucy", 40],[3, "mary",50]]
for lists in nested_list:
if lists[0] == 3 and lists[1] == 'mary':lists[2] += 10
输入
[[1,"adam", 20],[2, "lucy", 40],[3, "mary",50]]
输出
[[1, 'adam', 20], [2, 'lucy', 40], [3, 'mary', 60]]
考虑以下嵌套列表:
nested_list = [[1, "adam", 20],
[2, "lucy", 40],
[3, "mary", 50]]
我想做以下条件举例:
搜索 '3' 关键字,如果找到则检查第二个元素是否为“mary”,然后更新第三个元素。
伪:
if '3' is found in nested_list then if index[1] == "mary" then index[2] = 50 + 10 (update)
你在伪代码上有一个位置,我们可以直接改成代码。你有基本的想法,遍历 nested_list
检查任何列表中的第一个元素是否等于 3
。然后我们需要检查第二个索引,看它是否等于 mary
。如果两个测试都通过,我们需要更新列表中的最后一个元素。
代码
nested_list = [[1,"adam", 20],[2, "lucy", 40],[3, "mary",50]]
for lists in nested_list:
if lists[0] == 3 and lists[1] == 'mary':lists[2] += 10
输入
[[1,"adam", 20],[2, "lucy", 40],[3, "mary",50]]
输出
[[1, 'adam', 20], [2, 'lucy', 40], [3, 'mary', 60]]