【问题标题】:How do I get data in tuples and tuples in lists?如何获取元组中的数据和列表中的元组?
【发布时间】:2017-05-09 08:34:43
【问题描述】:

我正试图弄清楚汽车在虚构的曼哈顿行驶的路线。 我已经定义了起始位置,是(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)也可以在括号之间,就像所有其他位置一样。如果我是对的,这与元组有关吗?

提前致谢!

【问题讨论】:

    标签: python list tuples


    【解决方案1】:

    这样的?

    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
    

    【讨论】:

    • 谢谢,你能解释一下我在这里看到的情况吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2016-12-19
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多