2011-07-14 390 views
46

我知道這是一個非常基本的問題,但我是python的新手,無法弄清楚如何解決它。python列表中的拆分元素

我有一個列表:

list = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847'] 

,我想之後刪除 '\ t' 和一切。我正在考慮將'\ t'中的每個元素分開,以便我可以刪除列表中的每一個其他元素。但是,當我試着做list[0:].split('\t')時,我得到了AttributeError:'list'對象沒有屬性'split'。我也嘗試將整個列表變成一個字符串,但這帶來了其他一系列問題。任何建議,將不勝感激。

+6

解釋爲什麼你的代碼沒有工作(不喜歡唯一的代碼解答初學者):'list [0:]'返回一個列表,所以你不能在'str'中使用'split',一個函數。感謝您的解釋,您必須遍歷每個元素並單獨拆分它,或者使用for或[list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) – Jacob

+0

。非常感激。 – user808545

+0

今天我瞭解到,總有一種更簡單的方法來做我想要的python – espais

回答

52

喜歡的東西:

>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847'] 
>>> [i.split('\t', 1)[0] for i in l] 
['element1', 'element2', 'element3'] 
+0

我幾乎明白這一點。分裂做法的論點是什麼?相同的,我認爲是索引0後parens。這是通過使用曾經是我的zeroeth元素創建一個新的列表嗎?那麼是另一個分裂,是否有效地擺脫了OP的其他部分? –

+0

由於列表包含字符串,因此變量i是一個字符串。所以i.split('\ t',1)調用字符串的split()方法。根據[documentation](https://docs.python.org/2/library/stdtypes.html#str.split),此方法的第一個參數是要分割的字符串,第二個參數是分割的最大數目去表演。該方法返回執行拆分後得到的字符串列表,因此「[0]」返回結果列表中的第一個拆分字符串。 – jcl

+1

當我爲自己的代碼嘗試這個時,它返回一個錯誤,即'list'對象沒有'split'屬性。我很困惑如何解決這個問題。 – keitereth24

25
myList = [i.split('\t')[0] for i in myList] 
3

嘗試通過列表中的每個元素進行迭代,然後在製表符分割它,將它添加到一個新的列表。

for i in list: 
    newList.append(i.split('\t')[0]) 
+4

這可行,但列表解析是一個更好的方法來做到這一點 – dave

+0

我不熟悉這種方法,謝謝你的提示。 – caltangelo

4

不要使用list作爲變量名。 你可以看看下面的代碼太:

clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5'] 
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist] 

或就地編輯:

for i,x in enumerate(clist): 
    if '\t' in x: 
     clist[i] = x[:x.index('\t')] 
-3
sentences = ("The cat ate a big mouse. This was becasue the mouse was annoying him") 

import re 

liste = re.findall(r"[\w']+|[.,!?;]", sentences) 

nodu = [] 
for x in liste: 
if x not in nodu: 
    nodu.append(x) 
print(nodu) 

pos = [] 
for word in liste: 
if word in nodu: 
    pos.append(nodu.index(word)+1) 
print(pos) 

lpos = [] 
for word in liste: 
lpos.append(liste.index(word)+1) 

nodus = (str(nodu)) 
file=open("t3.txt","w") 
file.write(nodus) 
file.write("\n") 
file.write(str(pos)) 
file.close() 



for number in lpos: 
for word in liste: 
    number = word 
    print(number) 
break