当前位置: 代码迷 >> python >> 如何将列表中的数据映射到元组?
  详细解决方案

如何将列表中的数据映射到元组?

热度:4   发布时间:2023-07-14 08:47:47.0

我想要这个

[('106', '1', '1', '43009'), ('106', '1', '2', '43179'), ('106', '1', '3', '43189'), ('106', '1', '4', '43619'), ('106', '1', '5', '43629')]

这是我的代码

def read_route_data(filename):
    with open(filename, 'r') as f:
        lines = list(f)
        return map(lambda x: x[:-1], lines) # [:-1] is to remove the last character


bus_stations = read_route_data('smrt_routes.txt')
print(bus_stations[:5]) 

我得到了['106,1,1,43009', '106,1,2,43179', '106,1,3,43189', '106,1,4,43619', '106,1,5,43629']而不是在元组中。 我该如何做才能使我的str在元组中? 我尝试了return map(lambda x:(x [:-1],),lines),这在后面给了我一个额外的逗号。

干得好:

>>> foo = ['106,1,1,43009', '106,1,2,43179', '106,1,3,43189', '106,1,4,43619', '106,1,5,43629']
>>> [tuple(f.split(",")) for f in foo]
[('106', '1', '1', '43009'), ('106', '1', '2', '43179'), ('106', '1', '3', '43189'), ('106', '1', '4', '43619'), ('106', '1', '5', '43629')]

我们使用列表.split()来过滤每个键,使用.split()将每个字符串拆分为一个列表,并使用tuple()将该列表转换为一个元组

  相关解决方案