Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将列表中的连续元素配对而不重叠?_Python_Python 3.x_List - Fatal编程技术网

Python 如何将列表中的连续元素配对而不重叠?

Python 如何将列表中的连续元素配对而不重叠?,python,python-3.x,list,Python,Python 3.x,List,简单问题:我有u=[1,2,3,4,5,6]。我想要v=[(1,2)、(3,4)、(5,6)]。怎么做 显然,一种解决办法是: v = [] for i in range(len(u)): j = 2*i v += [(u(j), u(j+1))] 但这是如此丑陋和跛脚,我讨厌每次看它,我这样做。有更好的方法吗?是一种肾盂疗法 list(zip(u[::2], u[1::2])) 这是一种肾盂疗法 list(zip(u[::2], u[1::2])) 对于不支持切片表示法的

简单问题:我有
u=[1,2,3,4,5,6]
。我想要
v=[(1,2)、(3,4)、(5,6)]
。怎么做

显然,一种解决办法是:

v = []
for i in range(len(u)):
    j = 2*i
    v += [(u(j), u(j+1))]
但这是如此丑陋和跛脚,我讨厌每次看它,我这样做。有更好的方法吗?

是一种肾盂疗法

list(zip(u[::2], u[1::2]))
这是一种肾盂疗法

list(zip(u[::2], u[1::2]))

对于不支持切片表示法的iterables,这里有一个更通用的解决方案

def n_clusters(iterable, n=2):
    return zip(*[iter(iterable)]*n)
请注意,输出中不包括任何剩余值(例如输入列表中的元素数为奇数)。我们可以使用函数来更正此问题

from itertools import zip_longest

def n_clusters(iterable, n=2, fillvalue=None):
    return zip_longest(*[iter(iterable)]*n, fillvalue=fillvalue)
以上两种方法都将返回分组值上的迭代器。您可以手动从它们中生成一个列表

grouped_values = list(n_cluster([1, 2, 3, 4]))
# [(1, 2), (3, 4)]
或者直接迭代它们

for a, b in n_cluster([1, 2, 3, 4]):
    ...

对于不支持切片表示法的iterables,这里有一个更通用的解决方案

def n_clusters(iterable, n=2):
    return zip(*[iter(iterable)]*n)
请注意,输出中不包括任何剩余值(例如输入列表中的元素数为奇数)。我们可以使用函数来更正此问题

from itertools import zip_longest

def n_clusters(iterable, n=2, fillvalue=None):
    return zip_longest(*[iter(iterable)]*n, fillvalue=fillvalue)
以上两种方法都将返回分组值上的迭代器。您可以手动从它们中生成一个列表

grouped_values = list(n_cluster([1, 2, 3, 4]))
# [(1, 2), (3, 4)]
或者直接迭代它们

for a, b in n_cluster([1, 2, 3, 4]):
    ...

我忘了你可以用Python做
[::2]
!我忘了你可以用Python做
[::2]