[英]Python Comma Separate List
I need help, I'm trying to code a comma separated list but the results to be printed in a different way. 我需要帮助,我正在尝试编写一个用逗号分隔的列表,但结果将以不同的方式打印。
Here is my example code: 这是我的示例代码:
a = ('name1', 'name2', 'name3')
b = ('url1', 'url2', 'url3')
results = (a, b)
print(results)
This will show: 这将显示:
(('name1', 'name2', 'name3'), ('url1', 'url2', 'url3'))
However, I would like it to show: 但是,我希望它显示:
name1, url1, name2, url2, name3, url3
Any help appreciated 任何帮助表示赞赏
Thanks 谢谢
You can first use zip(..)
to generate 2-tuples for each name and url, then we can use a generator or list comprehension to join these together, like: 您可以首先使用
zip(..)
为每个名称和url生成2元组,然后我们可以使用生成器或列表推导将它们组合在一起,例如:
print(', '.join(y for x in zip(a,b) for y in x))
This generates: 这将产生:
>>> print(', '.join(y for x in zip(a,b) for y in x))
name1, url1, name2, url2, name3, url3
Or a more declarative style: 或更声明性的样式:
from itertools import chain
print(', '.join(chain(*zip(a,b))))
EDIT : 编辑 :
If you want to print the url on separate lines, you can use: 如果要在单独的行上打印URL,可以使用:
for n,u in zip(a,b):
print(n,u,sep=',')
Or if you want to produce a string first: 或者,如果您想首先产生一个字符串:
print('\n'.join('{}, {}'.format(*t) for t in zip(a,b))
This should do the trick. 这应该可以解决问题。
a = ('name1', 'name2', 'name3')
b = ('url1', 'url2', 'url3')
from itertools import chain
ab = tuple(chain.from_iterable(zip(a, b)))
lst = ', '.join(ab)
There are a plethora of ways to do this, here is what first came to my mind. 有很多方法可以做到这一点,这是我首先想到的。
import operator
results = reduce(operator.add, zip(a, b))
Here is another more 'broken down' maybe ugly way of doing it, however it's easier to see what's going on. 这是另一种可能更丑陋的“分解”方法,但是更容易看到正在发生的事情。
results = []
while True:
try:
results.append(a.pop(0))
results.append(b.pop(0))
except IndexError:
break
Willem's answer is the way to go for your original question. 威廉的答案是您提出原始问题的方式。
If you want to do more than just display the elements, you might want to use a dict
for your data: 如果您想做的不仅仅是显示元素,还可以对数据使用
dict
:
>>> dict(zip(a,b))
{'name2': 'url2', 'name3': 'url3', 'name1': 'url1'}
If the order is important, you can use an OrderedDict
: 如果顺序很重要,则可以使用
OrderedDict
:
>>> from collections import OrderedDict
>>> OrderedDict(zip(a,b))
OrderedDict([('name1', 'url1'), ('name2', 'url2'), ('name3', 'url3')])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.