2012-02-05 38 views
1

我在Python中有一個列表。該列表中有子列表。 例如:在Python中刪除字符串中每個元素的第一項

[['85.', 'Document', 'will', 'discuss', 'allegations,', 'or', 'measures', 'being', 'taken', 'against,', 'corrupt', 'public', 'officials', 'of', 'any', 'governmental', 'jurisdiction', 'worldwide.'], ['56.', 'Document', 'will', 'include', 'a', 'prediction', 'about', 'the', 'prime', 'lending', 'rate,', 'or', 'will', 'report', 'an', 'actual', 'prime', 'rate', 'move.'], and so on] 

當我打印MYLIST [0],我得到如下:

['85.', 'Document', 'will', 'discuss', 'allegations,', 'or', 'measures', 'being', 'taken', 'against,', 'corrupt', 'public', 'officials', 'of', 'any', 'governmental', 'jurisdiction', 'worldwide.'] 

當我打印MYLIST [0] [0]我得到85.

我新的python和我不明白如何訪問這些值(85,56,等等)內循環,以便我可以刪除所有的數字。即85,56等等。

  1. 我也有一個類似的列表[[1, 23], [2, 34], [3, 45], [1, 45], [2, 44]] ,我想添加的所有的第二元件,其中第1個要素是相同的。即我想增加23 + 45(因爲兩者都有1作爲他們的第一個元素)。我知道我需要一個for循環,但我是python的新手,我無法理解循環。
+1

在你提出關於SO的基本問題之前,請閱讀[documentation](http://docs.python.org/tutorial/index.html)。它涵蓋了你剛剛提到的一切。 – 2012-02-05 22:39:59

回答

1

要得到所有的第一要素:

zip(*your_list)[0] 

zip(*some_iterable)做某種矩陣求逆的 - 你應該打幾分用它來獲得一個想法。

要從一組迭代中刪除所有第一個值,您可以選擇幾種方法。例如: -

[item[1:] for item in your_list] # probably the best 
zip(*zip(*your_list)[1:]) # tricky and probably slow one 

總結你的價值觀你需要一本字典:

>>> from collections import defaultdict 
>>> l = [[1, 23], [2, 34], [3, 45], [1, 45], [2, 44]] 
>>> d = defaultdict(int) 
>>> for item in l: 
    d[item[0]] += item[1] 

>>> d.items() 
[(1, 68), (2, 78), (3, 45)] 

我們使用defaultdict這裏能夠執行此d[item[0]] += item[1]分配新建分配FY。用簡單的dict我們會得到一個KeyError,因爲我們的d是空的。但defaultdict在這種情況下只是返回默認值 - int(),這是0

+0

打印zip(* mylist)[0]給我所有的數字。 [85.,56.等等]我如何顯示沒有數字的新的壓縮列表? – Nerd 2012-02-05 22:32:39

1

基本上,python將mylist [0] [0]的每個部分視爲2個單獨的命令。 第一個電話:mylist[0]回報

['85.', 'Document', 'will', 'discuss', 'allegations,', 'or', 'measures', 'being', 'taken', 'against,', 'corrupt', 'public', 'officials', 'of', 'any', 'governmental', 'jurisdiction', 'worldwide.'] 

這是你原來的列表中的第一項。第二部分獲得該列表的<first call>[0]或第0個元素。它應該返回85

爲了訪問下一個列表的第一個元素,你可以使用mylist[1][0](取得第二個元素,從這個列表返回第1個要素...

要獲得所有第一列表列表中的元素,使用列表理解:

first_items = [item[0] for item in mylist] 
    print(first_items) 
    ... 
    [85, 56,... and so on] 

要「刪除」所有的第一列表的元素,你會做些什麼叫做切片。您可以使用每個列表的第二個元素(等)的新名單:

new_list = [item[1:] for item in mylist] 
1

對於你的第一個問題:

first_values = [int(sublist[0]) for sublist in data] 

對於你的第二個問題:

x = [[1, 23], [2, 34], [3, 45], [1, 45], [2, 44]] 

dicto = {} 

for sublist in x: 
    try: 
     dicto[sublist[0]] = dicto[sublist[0]] + sublist[1] 
    except KeyError: 
     dicto[sublist[0]] = sublist[1] 
相關問題