[英]Selecting elements from Python array
I have used the code below to grab data from a CSV file and putting it into a list. 我使用下面的代码从CSV文件中获取数据并将其放入列表中。 The output is a series of lists, within lists, an array.
输出是一系列列表,列表中的一个数组。
I want to grab the first item form each row in the CSV file and assign it to a variable. 我想从CSV文件的每一行中获取第一项并将其分配给变量。 The code I developed works but is very long winded.
我开发的代码行得通,但是影响很长。 I'm interested in modifying the second part of the code if possible not the loop.
我有兴趣修改代码的第二部分,如果可能的话,不要修改循环。
with open('player1.csv', 'rb') as f:
reader = csv.reader(f)
your_list = list(reader)
print "First Player"
Player1 = your_list[0:1]
Player1name = (Player1[0:1])
Player1name = (Player1name[0])
Player1name = (Player1name[0])
print Player1name
What about putting the first item of each item of each row into an array instead of having a separate variable for each item? 将每行每个项目的第一项放入数组而不是为每个项目使用单独的变量怎么办?
So something like this using a list comprehension 所以这样使用列表理解
player_names = [row[0] for row in your_list]
And if you want to print them: 如果要打印它们:
for name in player_names:
print name
By the description provided, it is assumed that you would like to evaluate an instruction stored in a string
ie, Taken from: http://lucumr.pocoo.org/2011/2/1/exec-in-python/ 根据提供的描述,假定您要评估存储在
string
的指令, 即,取自: http : //lucumr.pocoo.org/2011/2/1/exec-in-python/
>>> code = compile('a = 1 + 2', '<string>', 'exec')
>>> exec code
>>> print a
3
However, this is a heavy procedure to execute each time you lookup each CSV fle. 但是,这是一个很繁琐的过程,每次您查找每个CSV文件时都要执行。 Why you would not use a Dictionary and add each variable with key
playerNname
. 为什么不使用Dictionary并使用key
playerNname
添加每个变量。 eg, playerDict = {'player1Name':var1, 'player2Name':var2, ..., 'playerNName':varN}
? 例如,
playerDict = {'player1Name':var1, 'player2Name':var2, ..., 'playerNName':varN}
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.