如果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的两个实例。如果我能够在列表的某个特定索引处添加值,那就太好了,但我可以解决这个问题。你知道吗
使用字典可能更容易做到这一点:
如果您必须使用列表,那么很容易临时转换为字典并返回列表:
与其使用
List1 + [valuestoadd[1:]]
,不如使用newlist[0].append(valuestoadd[1:])
,这样它就永远不会创建新列表,只会附加到旧列表。[0]
是必需的,因此它附加到第一个子列表而不是整个列表。你知道吗遗憾的是,这确实是将值作为列表输入的—如果要将它们拆分为单个值,则需要遍历正在添加的列表,并将单个值附加到
newlist[0]
。你知道吗这可以通过另一个
for
循环来实现,如下所示:我同意其他答案,即最好马上用词典。但是,如果出于某种原因,您希望保持现有的数据结构,您可以将其转换为字典并返回:
在创建新的\u列表时,只有在不希望包含所有键的情况下,才可以从类型为\u dict的子集中获取这些键。你知道吗
相关问题 更多 >
编程相关推荐