我想知道如何从列表列表中获取字符串值,并将这些值插入相应的元组列表中。
我可以从中获取值的地方:
[[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')]
模式将是从第一个代码段中获取字符串值,并将其插入到相应list []中每个元组的末尾。
# 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)]]
我想在其中插入颜色的是列表括号内的元组,希望这是有道理的:)
不确定,它符合您的需求,但是这里有个主意:
# res to store the results
# a is the first list
# b the 2nd
res=[0 for x in range(len(a))]
for i in range(len(a)):
res[i]=[]
for z in b[i]:
# from tuple to list
y=list(z)
# add the string (4th elt from the 1st array)
y.append(a[i][3])
# from list to tuple
zz=tuple(y)
# append to result
res[i].append(zz)
# print result
print(res)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句