2016-04-15 67 views
0

我想知道如何檢索列表索引處的第一個單詞。檢索列表索引中的第一個單詞python

例如,如果該列表是:

['hello world', 'how are you'] 

有沒有辦法讓x = "hello how"

這是我到目前爲止已經試過(newfriend是列表):

x="" 

for values in newfriend: 
     values = values.split() 
     values = ''.join(values.split(' ', 1)[0]) 
     x+=" ".join(values) 

x+="\n" 

回答

4

一個簡單的生成器表達式會做,我猜,例如

>>> l = ["hello world", "how are you"] 
>>> ' '.join(x.split()[0] for x in l) 
'hello how' 
+0

不在列表內!列表元素內部列表字符串!投票下來-1 – dsgdfg

+0

這個代碼有什麼問題?對不起,我剛開始Python – Lukaku

+1

@dsgdfg你能解釋你的downvote更好嗎? – zezollo

1

你不遠處。這是我會怎麼做的。

# Python 3 
newfriend = ['hello world', 'how are you'] 
x = [] # Create x as an empty list, rather than an empty string. 
for v in newfriend: 
    x.append(v.split(' ')[0]) # Append first word of each phrase to the list. 

y = ' '.join(x) # Join the list. 
print(y) 
0
import re 
#where l =["Hello world","hi world"] 
g=[] 
for i in range(l): 
    x=re.findall(r'\w+',l[i]) 
    g.append(x) 
print(g[0][0]+g[1][0]) 
相關問題