2014-01-16 85 views
0
a=['Business', 'Food/Clothes', 'Fun', 'Politics', 'Starting_with_Apolog', ['NNP', 'MD', 'NN', 'NNP'], ['NNP', 'NN', 'NNP'], ['PDT', 'MD', 'NN', 'NNP'], ['PRP$', 'MD', 'NN', 'NNP'], ['UH', 'MD', 'NN', 'NNP'], ['WP$', 'MD', 'NN', 'NNP'], 'end__with_ly', 'end_with_al', 'end_with_ful', 'end_with_ible', 'end_with_ic', 'end_with_ive', 'end_with_less', 'end_with_ous', 'sorry_word', 'Gender'] 

    f = open("file.csv") 
    reader = csv.reader(f) 
    headers = None 
    results = [] 
    for row in reader: 
     if not headers: 
      headers = [] 
      for i, col in enumerate(row): 
       if col in a: 
        # Store the index of the cols of interest 
        headers.append(i) 
      print headers  
     else: 
      results.append(list([row[i] for i in headers])) 
    return results 

上面的代碼是一個從FILE.CSV在列表讀取特定列,以便其結果將是在結果可用,但索引代碼只會索引以下的列:如何從CSV讀取列

** Fun 63 
** Food/Clothes 64 
** Politics 70 
** Business 73 
** end_with_al 75 
** end_with_ful 76 
** end_with_ible 77 
** end_with_ic 78 
** end_with_ive 79 
** end_with_less 80 
** end__with_ly 81 
** end_with_ous 82 
** sorry_word 83 
** Starting_with_Apolog 84 
** Gender 1487 

該代碼不索引列表中的列表 - 我怎樣才能讓代碼搜索它們呢? 注意:file.csv包含一些帶有1487列的數據; a包含來自file.csv的一些列。

+0

你確定你使用細分離? – BenjaminB

+0

是的......當然...... – user104853

+1

「a」中的子列表有什麼意義? – ForeverWintr

回答

1

爲什麼不直接刪除列表中的列表?

'Starting_with_Apolog', ['NNP', 'MD', 'NN', 'NNP'] 

變化:

'Starting_with_Apolog', 'NNP', 'MD', 'NN', 'NNP' 

它是一種簡單的技巧,但它可能是去做最簡單的方法。

編輯

好了,所以既然你想列表結構,我相信你將不得不放棄一些性能之內離開該列表。我能想到的解決這個問題的下一個最簡單的方法如下:

a=['Business', 'Food/Clothes', 'Fun', 'Politics', 'Starting_with_Apolog', ['NNP', 'MD', 'NN', 'NNP'], ['NNP', 'NN', 'NNP'], ['PDT', 'MD', 'NN', 'NNP'], ['PRP$', 'MD', 'NN', 'NNP'], ['UH', 'MD', 'NN', 'NNP'], ['WP$', 'MD', 'NN', 'NNP'], 'end__with_ly', 'end_with_al', 'end_with_ful', 'end_with_ible', 'end_with_ic', 'end_with_ive', 'end_with_less', 'end_with_ous', 'sorry_word', 'Gender'] 
newa = []  
for element in a: 
    if isinstance(element, list): 
     for el in element: 
      newa.append(el) 
    else: 
     newa.append(element) 
a = newa 
# Now use "a" or "newa" in the rest of your code. 

否則你if col in a:支票是會得到一大堆複雜得多...

希望這有助於!

0

您的問題是in不會自動測試列入a中的子列表。

>>> 'Fun' in a 
    True 
>>> 'NNP' in a 
    False 

>>> 'NNP' in a[5] #a[5] is the list ['NNP', 'MD', 'NN', 'NNP'] 
    True 
+0

@Dylan我想是列表 – user104853

+0

高清try_literal_eval(項目): 嘗試: 回報ast.literal_eval(項目) 除(SyntaxError錯誤,ValueError異常): 回報項目 A = [try_literal_eval(項目= STR(項目)。用class_label替換(「」,「」)) print 打印一個 其實class_label包含列表...所以如何使用[i] – user104853