成对清单列表

时间:2018-12-13 07:45:15

标签: python python-3.x list

我有两个列表,我想创建一个列表列表,但要维护订单,所以如果我有:

l1 = [1,2,3,2]
l2 = [2,3,4,1]

我想要:

ans = [[1,2],[2,3],[3,4],[2,1]]

它维护索引的顺序

谢谢!

5 个答案:

答案 0 :(得分:4)

您可以使用zip

ans = [[a, b] for a, b in zip(l1, l2)]
  • 关于here中的zip的很好的教程。

如果其中一个列表比另一个列表长,则可以使用zip_longest(记录在here中):

from iterators import zip_longest
l1 = [1,2,3,2,7]
l2 = [2,3,4,1]
ans = [[a, b] for a, b in zip_longest(l1, l2, fillvalue=0)]
# output: ans = [[1,2],[2,3],[3,4],[2,1],[7,0]]

答案 1 :(得分:2)

@eventOptions({ capture: false, passive: true })
handleClick(e: Event) { console.log('clicked'); }

render() {
    return html`<button @click=${this.handleClick}>Click Me</button>`
}

答案 2 :(得分:0)

编辑:izip仅适用于python2。在Python 3中,内置zip的功能与2.x中的itertools.izip相同(返回迭代器而不是列表

使用zip

l1 = [1,2,3,2]
l2 = [2,3,4,1]

zip(l1, l2)
# [(1, 2), (2, 3), (3, 4), (2, 1)]

请注意,zip返回list类型:

type(zip(l1, l2))
# <type 'list'>

这意味着zip一次计算所有列表,而当l1, l2大时,这将不节省内存。为了节省内存,请使用izipizip仅在请求时计算元素。

from itertools import izip
y = izip(l1, l2)

for item in y:
    print(item)
# (1, 2), (2, 3), (3, 4), (2, 1)

print(type(y))
# <itertools.izip object at 0x7f628f485f38>

答案 3 :(得分:0)

您可以简单地执行以下操作:

l1 = [1,2,3,2]
l2 = [2,3,4,1]

ans = zip(l1, l2) #convert to tuples

ans = map(list, ans) #convert every tuples to list

for pairs in ans:
    print pairs

答案 4 :(得分:0)

您可以使用type="image"函数来做到这一点。

zip ()函数采用可迭代项(可以为零或更多),使迭代器根据传递的可迭代项聚合元素,并返回元组的迭代器。

代码:

    public File createFolder(String fname){
    String myfolder=Environment.getExternalStorageDirectory()+"/"+"Download"+"/"+fname;
    File f=new File(myfolder);
    if(!f.exists())
        if(!f.mkdirs()){
            Toast.makeText(getActivity(), myfolder+" can't be created.", Toast.LENGTH_SHORT).show();
            Log.d("myfolder","cant create");
        }
        else{
            Toast.makeText(getActivity(), myfolder+" can be created.", Toast.LENGTH_SHORT).show();
            Log.d("myfolder","created");
            return f;
        }

    else{
        Toast.makeText(getActivity(), myfolder+" already exits.", Toast.LENGTH_SHORT).show();
        Log.d("myfolder","exist");
        return null;
    }

    return f;
}

输出:

zip
相关问题