简体   繁体   English

Python-修改列表中的列表

[英]Python - Modifying lists within a list

Consider myself a beginner with Python. 认为自己是Python的初学者。 I'm trying to do something I've not quite done before and am completely stumping myself. 我正在尝试做一些我以前没有做过的事情,并且完全让自己感到沮丧。

Hoping someone can give me a clue as which path to take on this. 希望有人可以给我一个线索,指出该走哪条路。

I have a number of lists within a larger list. 我在较大的列表中有许多列表。

I would like to iterate through the large list and modify data in each sub-list. 我想遍历大列表并修改每个子列表中的数据。 There are a number of common variables within each list, but not all lists will be the same. 每个列表中都有许多公共变量,但并非所有列表都相同。

Example: 例:

LIST = [
        ['Name: Dave', 'Age 28', 'Dogs', 'Football',],
        ['Name: Tony', 'Age 22', 'Beer', 'Star Wars', 'Hotdogs']
       ]

The end goal is to have 1 large list with each sublist converted to a dictionary. 最终目标是要有1个大型列表,并将每个子列表转换为字典。

Goal: 目标:

LIST = [
        {'Dave' : { 'Age' : '28' } {'Likes' : ['Dogs', 'Football']}},
        {'Tony' : { 'Age' : '22' } {'Likes' : ['Beer', 'Star Wars', 'Hotdogs']}}
       ]

The conversion to dictionary I will worry about later. 转换为字典,我以后会担心。 But I am struggling to get my head around working with each sub-list in a loop. 但是我正在努力使自己与一个子列表循环工作。

Any ideas would be highly appreciated. 任何想法将不胜感激。

Thanks! 谢谢!

list2 = []
for el in list1:
    list2.append( compute(el))

where compute is a method that will turn your list into the dictionary you want 在这里,compute是一种可以将您的列表变成您想要的字典的方法

Axnyff's answer is pretty much what you want ShadowRanger's comment on Axnyff's answer is definitely what you want. Axnyff的答案几乎就是您想要的 ShadowRanger对Axnyff的答案的评论绝对是您想要的。 List comprehensions are really cool! 列表理解真的很棒!

Simply iterating over the list with a for loop lets you work on each sub-list and do whatever you want to it. 只需使用for循环遍历列表,就可以在每个子列表上进行操作,并对其进行所需的操作。

It looks like you don't really want to modify the lists in place, rather you want to process each list into a dictionary (and extracting that process into a separate function is very good for readability), and put those new dictionaries into a new list. 似乎您并不是真的想要修改列表,而是想将每个列表处理成字典(并将该过程提取到一个单独的函数中对于提高可读性非常有用),然后将这些新字典放入一个新字典中清单。

EDIT: 编辑:

Also, as correctly mentioned in a down-voted answer, your dictionaries should probably be in the form: 另外,正如在投票否定的答案中正确提到的那样,您的字典可能应采用以下形式:

{'Name': 'Dave', 'Age': 28, 'Likes': ['Dogs', 'Football']}

Unless you actually want to use the dictionary to find their information by their name, in which case this is the correct syntax: 除非您实际上想使用字典按名称来查找其信息,否则这种情况是正确的语法:

{'Dave' : { 'Age' : 28, 'Likes' : ['Dogs', 'Football']}}
result = {}
temp = {}
for x in LIST:
      key = x[0][6:]
      key_1 = x[1][:3]
      value_1 = x[1][3:]
      key_2 = 'Likes'
      value_2 = x[2:]
      temp[key_1] = value_1
      temp[key_2] = value_2
      result[key] = temp
      temp = {}

Try this but as you know dictionary has no sequence , no guarantee for age to be second in dictionary 试试看,但是您知道字典没有序列,不能保证年龄在字典中排第二

Here's an answer to get your dictionary in both the ways mentioned by Tom Ellis. 这是用汤姆·埃利斯(Tom Ellis)提到的两种方式获取字典的答案。

LIST = [
    ['Name: Dave', 'Age 28', 'Dogs', 'Football', ],
    ['Name: Tony', 'Age 22', 'Beer', 'Star Wars', 'Hotdogs']
]

l = list()
for li in LIST:
    d = dict()
    likes_list = []
    for i in li:
        if "name" in i.lower():
            d.update(dict([i.replace(' ', '').split(":")])) #removing the whitespace for formatting.
        elif "age" in i.lower():
            d.update(dict([i.split()]))
        else:
            likes_list.append(i)
    d["likes"] = likes_list

    l.append(d)
print l

Which results in: 结果是:

>>> [{'Age': '28', 'Name': 'Dave', 'likes': ['Dogs', 'Football']}, {'Age': '22', 'Name': 'Tony', 'likes': ['Beer', 'Star Wars', 'Hotdogs']}]

If you really want the dictionary in the format you stated first, you could continue with the program like this: 如果您确实希望字典具有您首先陈述的格式,则可以继续执行以下程序:

l2 = []
for element in l:
    nd = {}
    name = element.pop("Name").strip()
    nd[name] = element
    # print nd
    l2.append(nd)
print l2

Which results in the way you stated: 结果就是您所说的:

>>> [{'Dave': {'Age': '28', 'likes': ['Dogs', 'Football']}}, {'Tony': {'Age': '22', 'likes': ['Beer', 'Star Wars', 'Hotdogs']}}]
LIST=[{'Name': 'Dave', 'Age': 28, 'likes':['Dogs', 'Football']},{'Name': 'Tony', 'Age': 22, 'likes':['Beer', 'Star Wars', 'Hotdogs']}]

你喜欢这个,谢谢。

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

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