简体   繁体   English

带有2d数组的Python .join()

[英]Python .join() with a 2d array

Say I have this array: 说我有这个数组:

foo = [["a", "b"], ["c", "d"]]

If I want to print the elements of the inner arrays, I would do something like this: 如果要打印内部数组的元素,则可以执行以下操作:

for array_ in foo:
    for element in array_:
        print element

After doing this, I would get this result: 完成此操作后,我将得到以下结果:

a
b
c
d

How can I print each inner array vertically, then join it with the other array, like this? 我如何垂直打印每个内部数组,然后将其与另一个数组连接,像这样?

ac
bd

One way is to use zip() : 一种方法是使用zip()

>>> foo = [["a", "b"], ["c", "d"]]
>>> [''.join(a) for a in zip(*foo)]
['ac', 'bd']

zip(*foo) returns list of tuples, where the i-th tuple contains the i-th element from each of the input lists. zip(*foo)返回元组列表,其中第i个元组包含每个输入列表中的第i个元素。 And join() concatenates the content of the lists. join()连接列表的内容。

If the lists in the list of lists variable foo are large, you could use an efficient version of zip() from the itertools module: 如果列表变量foo的列表中的列表很大,则可以从itertools模块中使用zip()的高效版本:

>>> from itertools import izip
>>> foo = [["a", "b"], ["c", "d"]]
>>> [''.join(a) for (a) in izip(*foo)]
['ac', 'bd']

A shorter version using map() : 使用map()较短版本:

import operator as op
map(op.add ,*foo)
=> ['ac', 'bd']

map will work also: map也将起作用:

["".join(x) for x in map(None,*foo)]

Just join again to get just the strings: 只需再次加入即可获得字符串:

"\n".join(["".join(x) for x in map(None,*foo)])

In this case map behaves like zip, it transposes the elements: 在这种情况下,地图的行为就像zip,它会转置元素:

In [39]: foo = [["a", "b"], ["c", "d"]]

In [40]: map(None,*foo)
Out[40]: [('a', 'c'), ('b', 'd')]
In [1]: foo = [["a", "b"], ["c", "d"]]

In [2]: print "\n".join("".join(f) for f in zip(*foo))
ac
bd

The inner call to zip will transpose the array: 内部对zip调用将转置数组:

In [3]: zip(*foo)
Out[3]: [('a', 'c'), ('b', 'd')]

The first join will concatenate each tuple together: 第一个join将串连每个元组在一起:

In [4]: ["".join(element) for element in zip(*foo)]
Out[4]: ['ac', 'bd']

Finally each element in the list is joined by the outer call to join 最后,在列表中的每个元素由外呼叫连接到join

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

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