python - Python:如何从列表列表中获取值并将它们插入到元组列表中
问题描述
我想知道如何从列表列表中获取字符串值,并将这些值插入到相应的元组列表中。
我可以从哪里获取值:
[[0, 92, 8, 'GREEN'], [0, 82, 18, 'RED']]
我想将字符串值插入到下面的元组的尊重列表中:
[[(0, 92, 8), (0, 93, 7), (0, 91, 9), (1, 92, 7), (1, 91, 8)],
[(0, 82, 18), (0, 83, 17), (0, 81, 19), (1, 82, 17), (1, 81, 18)]
所以输出应该是这样的:
[[(0, 92, 8, 'GREEN'), (0, 93, 7, 'GREEN'), (0, 91, 9, 'GREEN'), (1, 92, 7, 'GREEN'), (1, 91, 8, 'GREEN')],
[(0, 82, 18, 'RED'), (0, 83, 17, 'RED'), (0, 81, 19, 'RED'), (1, 82, 17, 'RED'), (1, 81, 18, 'RED')]
该模式是从第一个代码片段中获取字符串值,并将其插入到相应列表 [] 中每个元组的末尾。
# to try and clear it up
[[0, 92, 8, 'GREEN'] # lets call this list 1
[0, 82, 18, 'RED']] # and this list 2
# list 1 corresponds with this list of lists of tuples
[[(0, 92, 8), (0, 93, 7), (0, 91, 9), (1, 92, 7), (1, 91, 8)]
# list 2 corresponds with this list of lists of tuples
[(0, 82, 18), (0, 83, 17), (0, 81, 19), (1, 82, 17), (1, 81, 18)]
有任何想法吗?如果这个问题不清楚,请发表评论,以便我解决:)
编辑:
我刚刚意识到我不能将值插入到元组中,因为它们是不可变的。如何将元组列表列表转换为我可以使用的列表?
进一步编辑:为了包含更多信息并进一步澄清,我希望能够在其自己的列表中选择每个元组并获得包含正确颜色的副本。一个例子:
#code1 #code2 #code3
[[0, 92, 8, 'GREEN'], [0, 82, 18, 'RED'], [0, 73, 27, 'GREEN']]
# shortened example; each open and close of [] should correspond
# to the above colour codes
# 1st set of [] = #code1 ('GREEN') to be inserted for each tuple
[[(0, 92, 8), (0, 93, 7)],
# 2nd set of [] = #code2 ('RED') to be inserted for each tuple
[(0, 91, 9), (1, 92, 7)],
# 3rd set of [] = #code3 ('GREEN') to be inserted for each tuple
[(1, 91, 8),[(0, 82, 18)]]
我想将颜色插入列表括号内的元组,希望这是有道理的:)
解决方案
这应该给你一些想法:
colors = [[0, 92, 8, 'GREEN'], [0, 82, 18, 'RED']]
d = {tuple(x[:3]):(x[3],) for x in colors}
lists = [[(0, 92, 8), (0, 93, 7), (0, 91, 9), (1, 92, 7), (1, 91, 8)],
[(0, 82, 18), (0, 83, 17), (0, 81, 19), (1, 82, 17), (1, 81, 18)]]
new_lists = [[t+d[sublist[0]] for t in sublist] for sublist in lists]
print(new_lists)
#prints [[(0, 92, 8, 'GREEN'), (0, 93, 7, 'GREEN'), (0, 91, 9, 'GREEN'), (1, 92, 7, 'GREEN'), (1, 91, 8, 'GREEN')], [(0, 82, 18, 'RED'), (0, 83, 17, 'RED'), (0, 81, 19, 'RED'), (1, 82, 17, 'RED'), (1, 81, 18, 'RED')]]
当我创建字典时,我创建了长度为 1 的值元组,因为我希望能够将它们连接到子列表中的元组上。请注意,这tuple('GREEN')
将是('G','R','E','E','N')
(长度为 5 的元组),而不是('GREEN',)
(长度为 1 的元组),这有望解释为什么我使用我使用的语法。