[英]Add tuples into a list without unpack the tuple
In Python, I have some tuples like b, and I want to add them into an empty list without unpack them. 在Python中,我有一些像b的元组,我想将它们添加到一个空列表中而不将它们解包。 Here, I simplify b so that it repeats itself, in reality, the values in b would be different, so b would be b1, b2, b3... 在这里,我简化b使其重复,实际上,b中的值将不同,因此b将为b1,b2,b3 ...
b = ({'a': 1, 'b': 1, 'c': 1}, 'y')
bb = [b, b, b]
print(len(bb))
print(len(bb[0]))
bb
This gives 这给
3 2 Out[204]: [({'a': 1, 'b': 1, 'c': 1}, 'y'), ({'a': 1, 'b': 1,'c': 1}, 'y'), ({'a': 1, 'b': 1, 'c': 1}, 'y')]
which is what I want. 这就是我想要的。 But since I am now doing in a loop, I can not write bb = [b, b, b]. 但是由于我现在处于循环状态,所以无法写bb = [b,b,b]。 The syntax I came up with will make hiarachy that I do not want. 我提出的语法会使我不想要的层次结构。
bb = ()
b = ({'a': 1, 'b': 1, 'c': 1}, 'y')
bb = [bb, b]
# in reality I loop bb with 3 times in for loop
bb = [bb, b]
bb = [bb, b]
print(len(bb))
print(len(bb[0]))
bb
This gives 这给
[[[(), ({'a': 1, 'b': 1, 'c': 1}, 'y')], ({'a': 1, 'b': 1, 'c': 1},'y')], ({'a': 1, 'b': 1, 'c': 1}, 'y')]
and is not want I wanted. 并不想我想要。 How can I loop and reach the first outcome? 如何循环并达到第一个结果?
Just use list comprehension: 只需使用列表理解:
b = ({'a': 1, 'b': 1, 'c': 1}, 'y')
bb = [b for i in range(3)]
Output: 输出:
[({'a': 1, 'c': 1, 'b': 1}, 'y'), ({'a': 1, 'c': 1, 'b': 1}, 'y'), ({'a': 1, 'c': 1, 'b': 1}, 'y')]
Start with a list and use append
: 从列表开始并使用append
:
bb = []
b = ({'a': 1, 'b': 1, 'c': 1}, 'y')
for _ in range(3):
bb.append(b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.