我试图将列表值从一个列表插入到另一个列表,但以特定顺序插入,其中日期[0] 输入文本[1],日期[1] 输入文本[3] 等等。
dates=['21/11/2044', '31/12/2018', '23/9/3000', '25/12/2007']
text=['What are dates? ', ', is an example.\n', ', is another format as
well.\n', ', also exists, but is a bit ludicrous\n', ', are examples but more commonly used']
我试过这个方法:
for j in range(len(text)):
for i in range(len(dates)):
text.insert(int((j*2)+1), dates[i])
这是错误的结果:
['What are dates? ', '25/12/2007', '23/9/3000', '25/12/2007', '23/9/3000',
'25/12/2007', '23/9/3000', '25/12/2007', '23/9/3000', '25/12/2007',
'23/9/3000', '31/12/2018', '21/11/2044', '31/12/2018', '21/11/2044',
'31/12/2018', '21/11/2044', '31/12/2018', '21/11/2044', '31/12/2018',
'21/11/2044', ', is an example.\n', ', is another format as well.\n', ',
also exists, but is a bit ludicrous\n', ', are examples but more commonly used']
我试图取回一个列表,内容如下:
['What are dates? ','21/11/2044', 'is an example.\n','31/12/2018', ', is
another format as well.\n','23/9/3000', ', also exists, but is a bit
ludicrous\n', '25/12/2007',', are examples but more commonly used']
有没有办法按照我想要的方式将日期[i]插入文本[2*j+1]?我什至应该使用 for
循环,还是有其他方法可以不在日期中列出所有内容?
最佳答案
实现此目的的更简单方法是使用 itertools.zip_longest
在 Python 3.x 中(或在 Python 2.x 中为 izip_longest
)为:
>>> from itertools import zip_longest # for Python 3.x
>>> # For Python 2.x
>>> # from itertools import izip_longest
>>> dates=['21/11/2044', '31/12/2018', '23/9/3000', '25/12/2007']
>>> text=['What are dates? ', ', is an example.\n', ', is another format as well.\n', ', also exists, but is a bit ludicrous\n', ', are examples but more commonly used']
>>> [w for x in zip_longest(text, dates, fillvalue='') for w in x if w]
['What are dates? ', '21/11/2044', ', is an example.\n', '31/12/2018', ', is another format as well.\n', '23/9/3000', ', also exists, but is a bit ludicrous\n', '25/12/2007', ', are examples but more commonly used']
您的代码的问题在于您嵌套了 for
循环,这就是为什么对于 j
的每个索引,dates
的所有值正在添加。
关于python - 在 Python 中以特定顺序将列表值从列表插入到另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48137882/