2017-06-03 29 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)。

相關問題