简体   繁体   English

在创建新“标签”时在列表中添加列表

[英]Add list within list while creating a new 'label'

I have 2 lists;我有 2 个列表; or at least, I believe they are lists:或者至少,我相信它们是列表:

one = [{'sex': 'M', 'age': 22},
      {'sex': 'M', 'age': 76},
      {'sex': 'F', 'age': 37},
      {'sex': 'F', 'age': 45}]

two = [0, 1, 0, 0]

I want to append the list two to the list one while creating a new 'label'.我想在创建新“标签”时将列表two的 append 添加到列表one中。

The desired output should look like this (and still be a list):所需的 output 应如下所示(并且仍然是一个列表):

[{'sex': 'M', 'age': 22, 'new label': 0},
 {'sex': 'M', 'age': 76, 'new label': 1},
 {'sex': 'F', 'age': 37, 'new label': 0},
 {'sex': 'F', 'age': 45, 'new label': 0}]

This must be easy but I can't make it work and couldn't use closely related answers on so.这一定很容易,但我不能让它工作,也不能在上面使用密切相关的答案。 Using just .append(two) put list two at the end of list one of course, instead of inserting it within list one .当然,仅使用.append(two)将列表two放在列表one的末尾,而不是将其插入列表one中。

Feel free to flag as duplicate if needed, but please help with this particular example!如果需要,请随意标记为重复,但请帮助处理这个特定示例! Many thanks非常感谢

for d, v in zip(one, two):
    d["new_label"] = v

one
# [{'sex': 'M', 'age': 22, 'new_label': 0},
#  {'sex': 'M', 'age': 76, 'new_label': 1},
#  {'sex': 'F', 'age': 37, 'new_label': 0},
#  {'sex': 'F', 'age': 45, 'new_label': 0}]

one is a list of dictionaries . one字典列表。 What you want to do is step through the dictionaries in said list, and append the values from two to it.你想要做的是遍历所述列表中的字典,以及 append 从two到它的值。

for i in range(0,len(one)):
    one[i]['age'] = two[i]

This steps through each dictionary in the list, and appends your new key-value pair to it.这将遍历列表中的每个字典,并将新的键值对附加到它。

So the first one is a list of dictionaries and the other is a list.所以第一个是字典列表,另一个是列表。

one = [{'sex': 'M', 'age': 22},
  {'sex': 'M', 'age': 76},
  {'sex': 'F', 'age': 37},
  {'sex': 'F', 'age': 45}]

two = [0, 1, 0, 0]

for count, i in enumerate(one):
    i['new label'] = two[count]

That would be how I would do it.那就是我会做的。 You can use enumerate to keep track of where you are in the loop.您可以使用枚举来跟踪您在循环中的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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