检索列表索引中的第一个单词python
问题描述:
我想知道如何检索列表索引处的第一个单词。检索列表索引中的第一个单词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"
答
一个简单的生成器表达式会做,我猜,例如
>>> l = ["hello world", "how are you"]
>>> ' '.join(x.split()[0] for x in l)
'hello how'
答
你不远处。这是我会怎么做的。
# 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)
答
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])
不在列表内!列表元素内部列表字符串!投票下来-1 – dsgdfg
这个代码有什么问题?对不起,我刚开始Python – Lukaku
@dsgdfg你能解释你的downvote更好吗? – zezollo