[('apples, 1,2,3,4,5,6,7,8,9,9,), ('banana, 1,2,46,7,8,5,345,2,1,4,), ('pear, ,7,8,5,6343,23,1,3,5,6,7,7,)]
以上数据位于外部csv文件中。我坚持写一个定义来获取数据并制作一个元组列表,其中包含名称字符串和数据点列表。字符串和数据点列表应位于元组
中所以(str,int[])
喜欢这样
答案 0 :(得分:3)
这比单线解决方案更具可读性!
def list_parser(l):
for t in l:
items = t[0].split(", ")
category = items[0]
number_strings = items[1:]
numbers = [float(n) for n in number_strings]
yield (category, numbers)
答案 1 :(得分:0)
您想使用列表理解。
[[i[0].split(",")[0], map(float, i[0].split(",")[1:])] for i in lst]
答案 2 :(得分:0)
这是一个有效的代码
x=[('apples, 21.72, 29.3, 20.08, 29.98, 29.85, 26.22, 19.99, 27.78, 27.02, 22.44, 26.54, 26.46, 22.24, 27.72, 22.25, 28.52, 25.57, 22.44, 27.06, 24.24, 21.74, 26.72, 27.23, 21.48, 26.14, 21.09, 28.28, 29.05, 23.52, 24.74, 29.08, 21.57, 21.98, 26.66, 21.99, 20.91, 28.07, 26.06, 22.54, 25.9, 21.78, 25.96, 25.25, 28.08, 23.79, 29.99, 21.41, 21.67, 22.94, 29.68',), ('banana, 57.51, 47.59, 55.89, 47.15, 46.71, 51.7, 46.68, 48.36, 52.15, 59.02, 45.1, 45.21, 51.13, 45.27, 57.24, 57.17, 49.47, 46.32, 42.47, 41.14, 46.86, 40.1, 58.67, 48.91, 48.21, 43.63, 43.11, 46.97, 52.07, 47.71, 53.27, 57.54, 56.19, 47.79, 45.32, 50.56, 51.23, 40.6, 48.03, 51.95, 54.54',), ('pear, 75.0, 82.43, 112.11, 89.93, 103.19, 80.6, 113.44, 105.44, 95.54, 121.98, 114.25, 109.84, 90.48, 105.84, 82.89, 113.64, 102.73, 104.57, 100.83, 75.59, 79.86, 91.11, 94.75, 109.89, 117.39, 74.71, 71.04, 92.97, 88.87, 92.95, 86.67, 101.46, 92.4, 85.2, 107.19, 117.81, 90.95, 82.02, 87.31, 106.53, 86.28, 106.62, 107.57, 89.38, 105.88, 74.45, 90.03, 107.96, 77.42, 98.9, 109.81, 102.51, 116.71, 82.92, 81.78, 74.42, 76.27, 73.84, 75.55, 102.29, 108.1, 98.84, 101.48, 77.75, 98.57, 70.31, 78.28, 80.18',)]
print [(i[0].split(",")[0],map(ast.literal_eval,[i.strip() for i in i[0].split(",")[1:]])) for i in x]
输出:
[('apples', [21.72, 29.3, 20.08, 29.98, 29.85, 26.22, 19.99, 27.78, 27.02, 22.44, 26.54, 26.46, 22.24, 27.72, 22.25, 28.52, 25.57, 22.44, 27.06, 24.24, 21.74, 26.72, 27.23, 21.48, 26.14, 21.09, 28.28, 29.05, 23.52, 24.74, 29.08, 21.57, 21.98, 26.66, 21.99, 20.91, 28.07, 26.06, 22.54, 25.9, 21.78, 25.96, 25.25, 28.08, 23.79, 29.99, 21.41, 21.67, 22.94, 29.68]), ('banana', [57.51, 47.59, 55.89, 47.15, 46.71, 51.7, 46.68, 48.36, 52.15, 59.02, 45.1, 45.21, 51.13, 45.27, 57.24, 57.17, 49.47, 46.32, 42.47, 41.14, 46.86, 40.1, 58.67, 48.91, 48.21, 43.63, 43.11, 46.97, 52.07, 47.71, 53.27, 57.54, 56.19, 47.79, 45.32, 50.56, 51.23, 40.6, 48.03, 51.95, 54.54]), ('pear', [75.0, 82.43, 112.11, 89.93, 103.19, 80.6, 113.44, 105.44, 95.54, 121.98, 114.25, 109.84, 90.48, 105.84, 82.89, 113.64, 102.73, 104.57, 100.83, 75.59, 79.86, 91.11, 94.75, 109.89, 117.39, 74.71, 71.04, 92.97, 88.87, 92.95, 86.67, 101.46, 92.4, 85.2, 107.19, 117.81, 90.95, 82.02, 87.31, 106.53, 86.28, 106.62, 107.57, 89.38, 105.88, 74.45, 90.03, 107.96, 77.42, 98.9, 109.81, 102.51, 116.71, 82.92, 81.78, 74.42, 76.27, 73.84, 75.55, 102.29, 108.1, 98.84, 101.48, 77.75, 98.57, 70.31, 78.28, 80.18])]