Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List_Slice - Fatal编程技术网

Python 使用单步执行从多个子列表中提取第二个元素

Python 使用单步执行从多个子列表中提取第二个元素,python,list,slice,Python,List,Slice,最初,我有一个坐标列表,用于在表格中绘制“之字形”图案: [10,10,20,20,30,10,40,20] 我想检查y坐标的所有“顶部”值是否相同,以便模式能够正常工作。我通过以下方式提取它们: a_vals = coords[1::4] 这给了我一个新的列表,所有元素都是10。我还重复了这一点,以检查每个第二个坐标的y部分是否为20 但是,现在坐标已拆分为子列表,在子列表中,我仍然需要将它们全部提取到一个新列表中(所有值分别为10和20,以便稍后检查): 根据我收集到的信息,应该可以对

最初,我有一个坐标列表,用于在表格中绘制“之字形”图案:

[10,10,20,20,30,10,40,20]
我想检查y坐标的所有“顶部”值是否相同,以便模式能够正常工作。我通过以下方式提取它们:

a_vals = coords[1::4]
这给了我一个新的列表,所有元素都是10。我还重复了这一点,以检查每个第二个坐标的y部分是否为20


但是,现在坐标已拆分为子列表,在子列表中,我仍然需要将它们全部提取到一个新列表中(所有值分别为10和20,以便稍后检查):


根据我收集到的信息,应该可以对其进行切片,但我不太确定如何使用所涉及的子列表进行切片,要记住它必须转到下一个子列表以提取值。

您可以使用列表理解来进行此操作,同时对列表进行切片-

a_vals = [y for x,y in coords[::2]]
这将获得所有的顶部坐标y值,对于其他y值,您只需将上面的切片更改为
coords[1::2]

演示-

>>> coords = [[10,10],[20,20],[30,10],[40,20]]
>>> a_vals = [y for x,y in coords[::2]]
>>> a_vals
[10, 10]
>>> b_vals = [y for x,y in coords[1::2]]
>>> b_vals
[20, 20]

您的实际数据的格式为[x,y,x,y,…]?@thefourtheye完全正确,然后我需要更改它,以便程序将接受[[x,y],[x,y],…],并提取我需要的元素。
>>> coords = [[10,10],[20,20],[30,10],[40,20]]
>>> a_vals = [y for x,y in coords[::2]]
>>> a_vals
[10, 10]
>>> b_vals = [y for x,y in coords[1::2]]
>>> b_vals
[20, 20]
>>> L = [10,10,20,20,30,10,40,20] 
>>> L1 = [x for x in L[::2]] # First Elements
>>> L1
[10, 20, 30, 40]
>>> L2 = [x for x in L[1::2]] # Second Elements
>>> L2
[10, 20, 10, 20]
>>> [[x, y] for x, y in zip(L1, L2)] # Group Them
[[10, 10], [20, 20], [30, 10], [40, 20]]