有没有一种方法可以使用导入的csv中的字符串生成列表名称?

时间:2019-05-14 23:08:35

标签: python csv import

我正在尝试导入一个csv文件,该文件的文本字符串输入很多,后跟几个值。像这样:

FruitBat, 20, 46, 12, 45. RocketTurtle, 45, 22, 17, 90

我希望能够导入此csv,以便它自动生成名为FruitBatRocketTurtle的列表,如下所示:

FruitBat = [20, 46, 12, 45]RocketTurtle=[45, 22, 17, 90]

我要导入的实际文件是几百个输入。有什么好办法吗?谢谢。

2 个答案:

答案 0 :(得分:0)

除非特别需要分别制作变量,否则将它们作为键值对存储在字典中会更容易。

您可以读取文件并将第一个元素用作键,并将其余元素切成列表。

import csv

# dictionary to hold all the lists
output_dict= {}

with open('file.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        # store key-value pairs
        output_dict[row[0]] = row[1:]

# get the corresponding values
print(output_dict["FruitBat"])

如果您真的想创建单独的变量,可能值得研究globals()

答案 1 :(得分:0)

您可以用逗号分隔字符串,然后使用数据制作字典:

import re

arr = yourString.split(",")

players = {} #I'm calling them players; I don't really know what they are

currentPlayer = arr[0]

players[currentPlayer] = []

for i in range( len(arr) ):
    if not re.search('[A-Za-z]', arr[i]): #If there are no letters in it
        players[currentPlayer].append(arr[i]) #add it to that player
    else: #If there were letters in it
        currentPlayer = arr[i]
        players[currentPlayer] = []

print(players)

我希望这会有所帮助!

编辑: 我没有意识到您的“玩家”数据之间用句点分隔。在这种情况下,您可以执行类似的操作:


import re

players_arr = yourString.split(".")

players = {}

for i in range( len(players_arr) ):
    data = players_arr[i].split(",")
    player = ""
    for j in range( len(data) ):
        if not re.search('[A-Za-z]', data[j]):
            players[player].append(data[j])
        else:
            player = data[j].strip()
            players[player] = []

print(players)