How do I get data in tuples and tuples in lists?

。_饼干妹妹 提交于 2019-12-16 18:05:12

问题


I am trying to figure out the route that a car takes in a fictional manhattan. I have defined the starting position, being(1,2)(in a 2 dimensional grid).

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))

i am doing this because I do not want a list in a list

route1=car

The first position in the route is where the car starts. I start a for loop that looks at which person is closest to my car. This person needs to be picked up, this location should be appended to the list for the route.

printing this result gives:

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

the dots in the brackets are correctly filled, I have intentionally left them 'blank' here.

the problem is that I do not know how this starting position for the car, (1,2) can also be between brackets, just like all the other locations. This has to do with tuples, if I am correct?

Thanks in advance!


回答1:


Something like this?

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

Output:

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

Explanation:

[(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


来源:https://stackoverflow.com/questions/41304799/how-do-i-get-data-in-tuples-and-tuples-in-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!