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

时间:2014-03-09 13:25:43

标签: python

我想得到这个

[('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在元组中?我试过返回地图(lambda x:(x [: - 1],),行),后面给了我一个额外的逗号。

1 个答案:

答案 0 :(得分:1)

你走了:

>>> 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()将每个字符串拆分为一个列表,tuple()将该列表转换为元组

相关问题