简体   繁体   English

如何将 python 列表转换为 1/2 行的元组列表?

[英]how to transform a python list to a list of tuple in 1/2 lines?

Input: ['a','b','c','d','e']输入: ['a','b','c','d','e']

Output: [('a','b'),('c','d'),('e')] Output: [('a','b'),('c','d'),('e')]

How can I do it in 1 or 2 lines of code?我怎样才能在 1 或 2 行代码中做到这一点?

For the moment I have this:目前我有这个:

def tuple_list(_list):
    final_list = []
    temp = []
    for idx, bat in enumerate(_list):
        temp.append(bat)
        if idx%2 == 1:
            final_list.append(temp)
            temp = []
    if len(temp) > 0: final_list.append(temp)
    return final_list
        
tuple_list(['a','b','c','d','e'])

You can use list comprehension.您可以使用列表理解。 First we will have a range with a step of 2. Using this we will take proper slices from the input list to get the desired result:首先,我们将有一个步长为 2 的范围。使用它,我们将从输入列表中获取适当的切片以获得所需的结果:

lst = ['a','b','c','d','e']
result = [tuple(lst[i:i+2]) for i in range(0, len(lst), 2)]

Try this list comprehension试试这个列表理解

x = ['a','b','c','d','e']
[(x[i],x[i+1]) for i in range(0,len(x)-1) if i%2==0]
x = ['a','b','c','d','e']
y = [tuple(x[i:i+2]) for i in range(0,len(x),2)]

You can slice the array by moving a sliding window of size 2 over your list.您可以通过在列表上移动大小为 2 的滑动 window 来对数组进行切片。

range(start, end, step) helps you to move window by step(2 in your case) while slicing helps you create smaller list out of bigger list. range(start, end, step) 可帮助您逐步移动 window(在您的情况下为 2),而切片可帮助您从较大的列表中创建较小的列表。

All that put into a list comprehension gives you a desired output.所有放入列表理解的内容都会为您提供所需的 output。

You could create an iterator with the built in iter() function and pass that to the built zip() function.您可以使用内置的 iter() function 创建一个迭代器,并将其传递给内置的 zip() function。

l = ['a','b','c','d','e']
i = iter(l)
zip(i, i)

if you'd like to group by 3 you can pass it 3 times to zip()如果你想按 3 分组,你可以将它传递 3 次给 zip()

zip(i, i, i)

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

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