[英]Acessing elements in a list of tuples
Been searching around the site but I can not find a solution that seems to work for me.一直在该网站上搜索,但我找不到似乎对我有用的解决方案。 I have a list of what I am assuming are tuples with 2 elements in them each.我有一个我假设是元组的列表,每个元组中有 2 个元素。 I would like to iterate over the list with tuples and break apart each tuple into a list.我想用元组迭代列表并将每个元组分解成一个列表。
data:数据:
[('A', 1), ('B', 2), ('C', 3)]
expected 2 lists countaining:预计有 2 个列表计数:
['A', 'B', 'C']
[1, 2, 3]
The most beautiful way to do this in a pythonic way is actually unzipping the tuples以pythonic方式执行此操作的最漂亮方法实际上是解压缩元组
zipped = [("a", 1), ("b", 2), ("C", 3)]
unzipped_object = zip(*zipped)
unzipped_list = list(unzipped_object)
print(unzipped_list)
output: output:
[('a', 'b', 'C'), (1, 2, 3)] [('a', 'b', 'C'), (1, 2, 3)]
Use list comprehension as:使用列表推导:
lst = [('A', 1), ('B', 2), ('C', 3)]
l1 = [elt[0] for elt in lst]
l2 = [elt[1] for elt in lst]
Or can be done in a single loop as:或者可以在一个循环中完成:
l1, l2 = [], []
for elt in lst:
l1.append(elt[0])
l2.append(elt[1])
If you are having a hard time with list comprehension here's the long and more readable version.如果您在列表理解方面遇到困难,这里是长且更具可读性的版本。 The other advantage is that this version is using a single for loop.另一个优点是这个版本使用了一个 for 循环。
lst = [('A', 1), ('B', 2), ('C', 3)]
list1 = []
list2 = []
for couple in lst:
list1.append(couple[0])
list2.append(couple[1])
print(list1)
print(list2)
you can use for loop.你可以使用 for 循环。
lst = [('A', 1), ('B', 2), ('C', 3)]
l1 = []
l2 = []
for tup in lst:
l1.append(tup[0])
l2.append(tup[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.