如何获取元组中的数据和列表中的元组?

2024-09-28 13:15:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出一辆汽车在虚构的曼哈顿所走的路线。 我已经定义了起始位置,即(1,2)(在二维网格中)。你知道吗

manhattan=[[1, 2, 3, 4, 5],
        [6, 7, 8, 9, 10],
        [11, 12, 13, 14, 15],
        [16, 17, 18, 19, 20]]

car_in_manhattan=8
car_unmerged = ([(index, row.index(car_in_manhattan)) for index, row in enumerate(manhattan) if car_in_manhattan in row])
car=list(itertools.chain(*car_unmerged))

我这样做是因为我不希望列表中有一个列表

route1=car

路线上的第一个位置是汽车的起点。 我开始一个for循环,看看哪个人离我的车最近。这个人需要被接走,这个位置应该被添加到路线的列表中。你知道吗

打印此结果会得到:

[1, 2, (.,.), (.,.), (.,.), (.,.), (.,.)] 

括号里的点是正确填写的,我故意把它们留空。你知道吗

问题是,我不知道这个起始位置的车,(1,2)也可以之间的括号,就像所有其他位置。这和元组有关,如果我是对的话?你知道吗

提前谢谢!你知道吗


Tags: in网格列表forindex定义路线car
1条回答
网友
1楼 · 发布于 2024-09-28 13:15:09

像这样的?你知道吗

a= [1, 2, (3,4), (5,6)] 
b=[(a[0],a[1])] + a[2:]
print b

输出:

[(1, 2), (3, 4), (5, 6)]

说明:

[(a[0],a[1])] + a[2:]

(a[0],a[1])    > Create a tuples from 1st and 2nd element of list a
[(a[0],a[1])]  > Enclose it in a list.
a[2:]       > Slice list a, extract all elements starting from index position 2

[(a[0],a[1])] + a[2:]  > add both the list

相关问题 更多 >

    热门问题