我认为这应该很容易,但我真的不知道如何以更好的方式写它,如果你知道请告诉我
#there are some points in text files and was read into a list
s = ['3,4','4,5','6,5','7,8']
#break s element to (x,y) form every element should convert to number type
points = []
for pStr in s:
ss = pStr.split(',')
points.append([int(p) for p in ss])
print(points) #[[3, 4], [4, 5], [6, 5], [7, 8]]
请更好地将其写在一行
答案 0 :(得分:6)
使用列表理解:
In [19]: s = ['3,4','4,5','6,5','7,8']
In [21]: [[int(y) for y in x.split(',')] for x in s]
Out[21]: [[3, 4], [4, 5], [6, 5], [7, 8]]
答案 1 :(得分:5)
如果使用Python 2.x,您可以执行以下操作:
points = [map(int, x.split(',')) for x in s]
如果使用Python 3.x,则需要将map()的结果传递给list(),因为它返回一个迭代器:
points = [list(map(int, x.split(','))) for x in s]
行动中:
>>> s = ['3,4','4,5','6,5','7,8']
>>> points = [map(int, x.split(',')) for x in s]
>>> print(points)
[[3, 4], [4, 5], [6, 5], [7, 8]]
答案 2 :(得分:1)
>>> s = ['3,4','4,5','6,5','7,8']
>>> from ast import literal_eval
>>> [literal_eval(x) for x in s]
[(3, 4), (4, 5), (6, 5), (7, 8)]
如果确实需要列表列表
>>> [list(literal_eval(x)) for x in s]
[[3, 4], [4, 5], [6, 5], [7, 8]]