Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.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_Tuples - Fatal编程技术网

在python中减去列表的第一个和最后一个元素

在python中减去列表的第一个和最后一个元素,python,list,tuples,Python,List,Tuples,我有以下清单: >>> list_of_lists = [[(0, 0)], [(6, 0)], [(7, 0), (8, 0), (9, 0)], [(10, 0)]] 我想要的是: >>> substract(list_of_lists) [6, 1, 1] 基本上我有一个列表。每个列表都是元组列表。我想从后续列表中第一个元组的第一个元素减去列表中最后一个元组的第一个元素。更象形的解释 [(0,0)],[(6,0)],[(7,0),(8,0),(9,0

我有以下清单:

>>> list_of_lists = [[(0, 0)], [(6, 0)], [(7, 0), (8, 0), (9, 0)], [(10, 0)]]
我想要的是:

>>> substract(list_of_lists)
[6, 1, 1]
基本上我有一个列表。每个列表都是元组列表。我想从后续列表中第一个元组的第一个元素减去列表中最后一个元组的第一个元素。更象形的解释

[(0,0)],[(6,0)],[(7,0),(8,0),(9,0)],[(10,0)]]

6-0=6

7-6=1


10-9=1

因此您可以使用索引访问此列表中的值。从那时起,你现在可以通过调用

list_of_list[1][0][0]
其中第一个索引引用列表中的列表,第二个索引引用列表中的元组,最后一个索引引用元组中的元素。另一个例子可能是访问8

list_of_list[2][1][0]
从那里,您应该能够自己创建一个循环,在列表中循环并输出所需的数组。

如何:

In [9]: ll = [[(0, 0)], [(6, 0)], [(7, 0), (8, 0), (9, 0)], [(10, 0)]]

In [10]: first = [l[0][0] for l in ll]

In [11]: last = [l[-1][0] for l in ll]

In [12]: [f - l for (f, l) in zip(first[1:], last[:-1])]
Out[12]: [6, 1, 1]
在这个解决方案中,列表只迭代一次(使用b),也就是说每个元素只分配一次


编辑:不,事实上,每个元素(即列表中的对象)第一次分配给b,然后再分配一次给a

“我想要的是,列表中的列表中的元组的第一个元素与上一个列表中的最后一个元组中的第一个元素相减。所以在substract(list)中发生以下情况:6-0=6,7-6=1,10-9=1,并在列表中给出结果。“这令人困惑。对于i==1,列表中的第二个和第一个元素必须通过其索引进行搜索。对于i==2,第三个和第二个元素必须通过它们的索引进行搜索,也就是说第二个元素必须进行第二次搜索。依此类推,因此每个元素必须搜索两次。-但是,我进行了测试,您的解决方案比我的解决方案快,这当然是因为它的索引比我的代码中的赋值花费更少的时间来查找元素-因此我建议您先创建一个对象,最后创建另一个对象,先创建第三个对象[1:],最后创建第四个对象[:-1],然后再创建一个对象(第一个[1],最后一个[:-1])。工作量太大了!我测试过:你的解决方案比我的解决方案长25%,比Squazic的解决方案长20%
[ll[i][0][0] - ll[i-1][-1][0] for i in xrange(1,len(ll))]
li = [[(0, 0)],
      [(6, 0)],
      [(7, 0), (8, 0), (9, 0)],
      [(10, 0)]]
for x in li:
    print x
print

def iti(li):
    a = li[0]
    for b in li[1:]:
        yield b[0][0]-a[-1][0]
        a = b

print list(iti(li))