当一个列表共享值时,将值从一个列表添加到另一个列表

2024-10-16 17:24:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如果List1中的类型相同,我尝试添加List2中的值。所有数据都是列表中的字符串。这不是我使用的确切数据,只是一个表示。这是我的第一个节目,请原谅我的误解。你知道吗

List1 = [['Type A =', 'Value 1', 'Value 2', 'Value 3'], ['Type B =', 'Value 4', 'Value 5']]
List2 = [['Type Z =', 'Value 6', 'Value 7', 'Value 8'], ['Type A =', 'Value 9', 'Value 10', 'Value 11'], ['Type A =', 'Value 12', 'Value 13']]

期望结果:

new_list =[['Type A =', 'Value 1', 'Value 2', 'Value 3', 'Value 9', 'Value 10', 'Value 11', 'Value 12', 'Value 13'], ['Type B =', 'Value 4', 'Value 5']]

当前尝试:

newlist = []
for values in List1:
    for valuestoadd in List2:
        if values[0] == valuestoadd[0]:
            newlist = [List1 + [valuestoadd[1:]]]
        else:
            print("Types don't match")
    return newlist

如果List2中没有两个类型A,这对我来说很有用,因为这会导致我的代码创建List1的两个实例。如果我能够在列表的某个特定索引处添加值,那就太好了,但我可以解决这个问题。你知道吗


Tags: 数据字符串in类型列表newforvalue
3条回答

使用字典可能更容易做到这一点:

def merge(d1, d2):
    return {k: v + d2[k] if k in d2 else v for k, v in d1.items()}

d1 = {'A': [1, 2, 3], 'B': [4, 5, 6]}
d2 = {'A': [7, 8, 9], 'C': [0]}
print(merge(d1, d2))

如果您必须使用列表,那么很容易临时转换为字典并返回列表:

from collections import defaultdict

def list_to_dict(xss):
    d = defaultdict(list)
    for xs in xss:
        d[xs[0]].extend(xs[1:])
    return d

def dict_to_list(d):
    return [[k, *v] for k, v in d.items()]

与其使用List1 + [valuestoadd[1:]],不如使用newlist[0].append(valuestoadd[1:]),这样它就永远不会创建新列表,只会附加到旧列表。[0]是必需的,因此它附加到第一个子列表而不是整个列表。你知道吗

newlist = List1 #you're doing this already - might as well initialize the new list with this code
for values in List1:
    for valuestoadd in List2:
        if values[0] == valuestoadd[0]:
            newlist[0].append(valuestoadd[1:]) #adds the values on to the end of the first list
        else:
            print("Types don't match")

Output:
[['Type A =', 'Value 1', 'Value 2', 'Value 3', ['Value 9', 'Value 10', 'Value 11'], ['Value 12', 'Value 13']], ['Type B =', 'Value 4', 'Value 5']]

遗憾的是,这确实是将值作为列表输入的—如果要将它们拆分为单个值,则需要遍历正在添加的列表,并将单个值附加到newlist[0]。你知道吗

这可以通过另一个for循环来实现,如下所示:

if values[0] == valuestoadd[0]:
    for subvalues in valuestoadd[1:]: #splits the list into subvalues
        newlist[0].append(subvalues) #appends those subvalues

Output:
[['Type A =', 'Value 1', 'Value 2', 'Value 3', 'Value 9', 'Value 10', 'Value 11', 'Value 12', 'Value 13'], ['Type B =', 'Value 4', 'Value 5']]

我同意其他答案,即最好马上用词典。但是,如果出于某种原因,您希望保持现有的数据结构,您可以将其转换为字典并返回:

type_dict = {}
for tlist in List1+List2:
    curr_type = tlist[0]
    type_dict[curr_type] = tlist[1:] if not curr_type in type_dict else type_dict[curr_type]+tlist[1:]
new_list = [[k] + type_dict[k] for k in type_dict]

在创建新的\u列表时,只有在不希望包含所有键的情况下,才可以从类型为\u dict的子集中获取这些键。你知道吗

相关问题 更多 >