2017-06-03 26 views
0

假设我想使用forloop自动生成大标题行的索引,以防止为每个标题写索引。如何使用for-loop使用列表元素的值自动生成变量?

在一个文件中,我说了一个包含很多水果名称的标题。每列都有一个数据,我必须使用索引访问下游解析。我不想为每个水果名称准备索引,而是希望运行forloop以实时创建索引值以节省时间。

data = 

     apple      banana    orange 
     genus:x,species:b genus:x,species:b  genus:x,species:b 
     genus:x,species:b genus:x,species:b  genus:x,species:b 
     variety:gala,pinklady,... variety:wild,hybrid... variety:florida,venz, 
     flavors:tangy,tart,sweet.. 
     global_consumption:.... 
     pricePerUnit:... 
     seedstocks:..... 
     insect_resistance:..... 
     producer:.... 


# first I convert the header into list like this: 

for lines in data: 
    if 'apple' in lines: 
     fruits = lines.split('\t') 
     # this will give me header as list: 
     # ['apple', 'banana', 'orange'] 

     # then create the index as:   
     for x in fruits: 
      str(x) + '_idx' = fruits.index(x) 
      # this is where the problem is for me .. !?? 
      # .. because this is not valid python method 
      print(x) 

      # if made possible, new variable are created as 
      apple_idx = 0, banana_idx = 1 ... so on 

# Now, start mining your data for interested fruits 
    data = lines.split('\t') 
    apple_values = data[apple_idx] 
    for values in apple_values: 
      do something ...... 

    same for others. I also need to do several other things. 

Make sense?? 

这怎么能成为可能?以一种非常简单的方式。

帖子编辑:做大量的阅读后,我意识到,这是可能的在bash创建使用其他varible的value(string)一个variable_name

how to use a variable's value as other variable's name in bash

https://unix.stackexchange.com/questions/98419/creating-variable-using-variable-value-as-part-of-new-variable-name

但是,在我看来,python是不可能的。我的直觉是,可以在python编程语言中编写这种方法(如果被黑客攻击或作者决定),但python的作者也有可能想到并了解可能的危险或使用这种方法。

  • 危险之处在于您总是希望variable_name在写入的python脚本中可见。准备一个动态variable_names本来不错,但如果出现任何问题,它可能会导致回溯时出现问题。
  • 因为变量名从来没有输入过,如果出现任何问题(特别是在大型程序中),比如说变量值类似于2BetaTheta*ping^pong这不是有效的变量名称,那将是一个噩梦来跟踪和调试。我的想法。 请其他人可以在为什么这个功能没有被引入python?
  • 字典方法结束了这个问题,因为我们有variable_name的起源记录,但仍然有效与无效variable_name的问题不会消失。

我打算采用dict method提供的答案,看看我能否找到一个非常简单而全面的方法来实现这一点。

谢谢大家!

+5

这是一个[XY问题](http://mywiki.wooledge.org/XyProblem) - 意思是说,你问的是你认为是你想解决的问题的一个很好的解决方案,而不是询问你试图解决的实际问题。没有理由用您尝试的方式命名具有不同名称的变量。你想要实现的是什么? –

+0

我想在variablename是(x-name +'_idx')时自动创建一个变量,它的值是它在该列表中的位置。 – everestial007

+0

也许你可以创建一本词典?然后你可以像dict [“apple”]那样访问它,并且你可以得到相应的索引。 – Antimony

回答

-1

内置函数execeval与此处相关。

Python documentation

  • eval: “expression参数被解析和评价为Python表达式”
  • exec: “此功能支持Python代码的动态执行”

真的,你只需要exec为你的问题,如下所示:

for fruit in fruits: exec('{0}_idx = fruits.index("{0}")'.format(fruit))

(请注意,我们需要在第二{}引号,否则Python会认为你正试图获得命名apple一些变量的指标,而不是将它的字符串'apple'

如果您现在键入apple_idx(例如)到您的控制台,它应该返回0

+1

喂养一个明显不知道自己在做什么的人,即使他们相信这样做,最终将他们向不应该去的方向发送也不会对他们有所帮助。 (downvote) –

+0

嗨瑞克,我认为有解决这个问题。我的蟒蛇不是很强大的工作方式,但总有一种方法。我了解X/Y问题。但是,这不是XY问题。应该有办法。 – everestial007

+0

我在告诉你:这是一个XY问题。我相信你相信它不是,但它肯定是。 –

1

编辑:现在,这个问题已被编辑如果我有时间,我会提供一个更有用的答案。

我不完全理解你究竟在做什么,但这里有一些可能有用的东西。

要承认的事情是你已经有一个对象,它包含你在它后面的所有信息:一个包含所有对象名称的列表。就其性质而言,您的名称列表已经包含索引。数据存在;它在那里。你需要做的是学会以正确的方式访问这些信息。

你可能需要的是enumerate function。这个函数生成一个两元组(这是一对对象)包含列表索引和列表中的内容,当您去:

for idx,fruit in enumerate(fruits): 
    print(fruit+'_idx: ', idx) 

没有理由来存储在其他一些数据结构,这些指标;他们已经在你的名单中。

如果你坚持要通过一些名字(字符串)来访问一些任意值,你应该做的是与字典,或dict

fruit_dict = dict() 
fruit_dict['apple'] = 1 

不过,既然你是指数后值,这似乎有点奇怪,因为dict本质上是打算无序。正如我所说,你已经知道列表中的索引。尽管可能会出现您想要这样做的情况,但第二次存储索引时最有可能没有意义。

2

希望下面的代码会给你一些想法,你可能会前进。实际上有些方法比这些做更好,但对于初学者来说,最好先学习基础知识。请注意:下面的代码没有什么错,但是如果我们使用了一些更高级的概念,它可能会更短,甚至更有用。

# get the headers from the first line out of the data 
# this won't work if the headers are not on the first line 
fruits = data[0].split('\t') 

# now you have this list, as before 
>>> ['apple', 'banana', 'orange'] 

# make a dictionary that will hold a data list 
# for each fruit; these lists will be empty to start 
# each fruit's list will hold the data appearing on 
# each line in the data file under each header 
data_dict = dict() 
for fruit in data_dict: 
    data_dict[fruit] = [] # an empty list 

# now you have a dictionary that looks like this 
>>> {'apple': [], 'banana': [], 'orange': []} 

# you can access the (now empty) lists this way 
>>> data_dict['apple'] 
[] 

# now use a for loop to go through the data, but skip the 
# first line which you already handled 
for lines in data[1:]: 
    values = lines.split('\t') 
    # append the values to the end of the list for each 
    # fruit. use enumerate so you know the index number 
    for idx,fruit in enumerate(fruits): 
     data_dict[fruit].append(values[idx]) 

# now you have the data dictionary that looks like this 
>>> {'apple': ['genus:x,species:b', 'genus:x,species:b'], 
    'banana': ['genus:x,species:b', 'genus:x,species:b'], 
    'orange': ['genus:x,species:b', 'genus:x,species:b']} 

print("<<here's some interesting data about apples>>") 
# Mine the data_dict for interesting fruits this way 
data_list = fruits['apple'] 
for data_line in data_list: 
    genus_and_species = data_line.split(',') 
    genus = genus_and_species[0].split(':')[1] 
    species = genus_and_species[1].split(':')[1] 
    print("\tGenus: ",genus,"\tSpecies: ",species) 

如果你想看看在所有的水果(如在之前的原始顺序),你能做到这一点是这样的:

for fruit in fruits: 
    data_list = data_dict[fruit] 
    for data_line in data_list: 
     print(data_line) 

如果你不关心顺序(dicts没有秩序*),你可以对你的水果名单,只是环比数据字典本身忘记:

for fruit in data_dict: 
    print(fruit) 

或获得的数值(数据表),使用values(在的Python 2.7):

for data_list in data_dict.values(): 
    print(data_list) 

或获得两个键(水果)和值,使用itemsviewitems在Python 2.7):

for fruit,data_list in data_dict.items(): 
    print(data_list) 

提示:如果您想变异(更改)字典,请勿使用for fruit in data_dict:。相反,您需要确保使用values,itemskeys(在Python 2.7中为viewkeys)方法。如果不这样做,你将有问题:

for fruit in data_dict.keys(): 
    # remove it 
    data_dict.pop(fruit) 

*快速注:dict■找了发生一些变化,这是非常有可能你将被允许认为他们会真正记得在即将到来的顺序下一个版本的Python(3.7)。

相关问题