简体   繁体   English

将元组附加到列表中

[英]Append tuples in order to a list

I'm new in python. 我是python的新手。 Is it possible to add my tuples to an empty list, but in an ordered way? 是否可以将我的元组添加到空列表中,但是以有序的方式?

The if i not in myTransfer: part is also not ideal I know, but just to get a clearer output. if i not in myTransfer:部分也不理想我知道,但只是为了获得更清晰的输出。 I tried doing it in the code below, but if there's an easier solution would be much appreciated 我尝试在下面的代码中执行此操作,但如果有更简单的解决方案将非常感激

tupDays = ('Monday', 'Wednesday', 'Monday')
tupAmount = (100,300,100)
myTransfer = []

for a in tupAmount:
    myTransfer.append(a)
    for i in tupDays:
        if i not in myTransfer:
            myTransfer.append(i)

print(myTransfer)

What I wanted to get is : 我想得到的是:

[100,Monday,200,Wednesday,100,Monday]

Maybe it will be better to put it in a dictionary, so it can become a key-value pairs, like below but I can't seem to grasp the built-in methods I need to use yet. 也许将它放在字典中会更好,所以它可以成为一个键值对,如下所示,但我似乎无法掌握我需要使用的内置方法。

{
100: 'Monday',
300: 'Tuesday',
100: 'Monday'
}

Thank you so much for the help.

An approach consists in using zip and itertools.chain . 一种方法包括使用zipitertools.chain
Here I'm assuming that the 2 tuples have the same length. 在这里,我假设2个元组具有相同的长度。

import itertools

my_transfer = list(itertools.chain(*zip(tupAmount, tupDays)))
# [100, 'Monday', 300, 'Wednesday', 100, 'Monday']

How it works: 这个怎么运作:

1) zip aggregates elements from the two tuples. 1)zip聚合来自两个元组的元素。

>>> list(zip(tupAmount, tupDays))
[(100, 'Monday'), (300, 'Wednesday'), (100, 'Monday')]

2) itertools.chain returns elements from the iterables. 2)itertools.chain返回迭代中的元素。 The star operator unpacks the list of tuples. 星型运算符解包元组列表。 This corresponds to: 这对应于:

>>> list(itertools.chain((100, 'Monday'), (300, 'Wednesday'), (100, 'Monday')))
[100, 'Monday', 300, 'Wednesday', 100, 'Monday']

3) finally, list() constructs a list 3)最后,list()构造一个列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM