如何从每行逗号之间提取数字是csv文件



我需要弄清楚如何将3个值从CSV文件中的行分离到新的列表中,以便稍后绘制到图形上。我已经将每一行分隔成一个列表,但是我需要新的列表来对每个以逗号分隔的值进行分类。

我已经将每一行分隔成一个列表,如下所示:

import csv
with open('Lottery_Powerball_Winning_Numbers__Beginning_2010.csv', 'r') as readObj:
heading = next(readObj)
csvReader = csv.reader(readObj)
listOfCSV = list(csvReader)
print(listOfCSV)

输出转述如下(由于字符限制,不能输出完整的输出)

['9/26/20', '11 21 27 36 62 24', '3'], ['9/30/20', '14 18 36 49 67 18', '2'], ['10/3/20', '18 31 36 43 47 20', '2'], ['10/7/20', '06 24 30 53 56 19', '2'], ['10/10/20', '05 18 23 40 50 18', '3']

您可以创建三个新列表,并读取您之前获得的行列表。

csv = [['9/26/20', '11 21 27 36 62 24', '3'], ['9/30/20', '14 18 36 49 67 18', '2'], ['10/3/20', '18 31 36 43 47 20', '2'], ['10/7/20', '06 24 30 53 56 19', '2'], ['10/10/20', '05 18 23 40 50 18', '3']]
date = []
number = []
end = []
for row in csv:
date.append(row[0])
number.append(row[1])
end.append(row[2])
print(date)
print(number)
print(end)

我将产生

['9/26/20', '9/30/20', '10/3/20', '10/7/20', '10/10/20']
['11 21 27 36 62 24', '14 18 36 49 67 18', '18 31 36 43 47 20', '06 24 30 53 56 19', '05 18 23 40 50 18']
['3', '2', '2', '2', '3']
代码是https://onecompiler.com/python/3yvns443z

如果你建立一个字典,那么它将很容易访问值的日期。例如,让我们假设CSV文件包含以下数据:

Date, Numbers, Multiplier
9/26/20, 11 21 27 36 62 24, 3
9/30/20, 14 18 36 49 67 18, 2
10/3/20, 18 31 36 43 47 20, 2
10/7/20, 06 24 30 53 56 19, 2
10/10/20, 05 18 23 40 50 18, 3

…然后…

import json # Only needed to prettify the output
data = dict()
with open('Lottery_Powerball_Winning_Numbers__Beginning_2010.csv') as csv:
next(csv) # skip column header
for line in csv:
try: # use try/ except in case any line does not contain exactly 3 tokens
date, numbers, multiplier = line.split(',')
data[date] = {'numbers': list(map(int, numbers.split())), 'multiplier': int(multiplier)}
except ValueError:
pass
print(json.dumps(data, indent=2))

输出:

{
"9/26/20": {
"numbers": [
11,
21,
27,
36,
62,
24
],
"multiplier": 3
},
"9/30/20": {
"numbers": [
14,
18,
36,
49,
67,
18
],
"multiplier": 2
},
"10/3/20": {
"numbers": [
18,
31,
36,
43,
47,
20
],
"multiplier": 2
},
"10/7/20": {
"numbers": [
6,
24,
30,
53,
56,
19
],
"multiplier": 2
},
"10/10/20": {
"numbers": [
5,
18,
23,
40,
50,
18
],
"multiplier": 3
}
}

相关内容

  • 没有找到相关文章

最新更新