Python 我如何将一个句子拆分成变量,然后列出它
我需要一个句子或一组单词,将每个单词分解成一个单独的变量,然后列出它们。这就是我到目前为止所做的:Python 我如何将一个句子拆分成变量,然后列出它,python,list,split,Python,List,Split,我需要一个句子或一组单词,将每个单词分解成一个单独的变量,然后列出它们。这就是我到目前为止所做的: sentence = input('Please type a sentence:') sentence.split(" ") words = [] words.extend([sentence.split(" ")]) print(words) 我使用单词“一二三”作为测试代码的输入。在这个示例语句中,预期的输出是[1,2,3],然后,我应该能够在以后对单独的变量执行所有操作:words[2
sentence = input('Please type a sentence:')
sentence.split(" ")
words = []
words.extend([sentence.split(" ")])
print(words)
我使用单词“一二三”
作为测试代码的输入。在这个示例语句中,预期的输出是[1,2,3]
,然后,我应该能够在以后对单独的变量执行所有操作:words[2]
问题是,列表“words”
只接收作为一个变量的拆分句子,因此输出变成[[1,2,3]]
,技术上只有一个变量
另外:我是一个完全不懂编程的人,这是我的第一篇博文,所以,如果我错过了一些明显的东西,请原谅我,
split
它会自己返回一个列表,然后你再放入另一个[]
,这样它就会嵌套起来
words.extend(sentence.split(" "))
或者您可以直接分配上面的列表
words = sentence.split(' ')
print (words)
#out
[one, two, three]
split
它自己返回一个列表,然后您再次放入另一个[]
以使其嵌套
words.extend(sentence.split(" "))
或者您可以直接分配上面的列表
words = sentence.split(' ')
print (words)
#out
[one, two, three]
使用
应该能解决你的问题<代码>拆分本身返回一个列表。使用
sentence = input('Please type a sentence:')
templist = sentence.split(" ")
words = []
for x in templist:
words.append(x)
print(words)
应该能解决你的问题<代码>拆分本身返回一个列表
sentence = input('Please type a sentence:')
templist = sentence.split(" ")
words = []
for x in templist:
words.append(x)
print(words)
或
备选方案:
sentence = input('Please type a sentence:')
words = sentence.split(" ")
print(words)
说明:
将句子设置为句子
变量
sentence = input('Please type a sentence:')
使用分隔符为空格的拆分函数拆分句子并存储在templist中
templist = sentence.split(" ")
迭代templist中的单词,并将每个单词附加到单词列表中
for x in templist:
words.append(x)
或
备选方案:
sentence = input('Please type a sentence:')
words = sentence.split(" ")
print(words)
说明:
将句子设置为句子
变量
sentence = input('Please type a sentence:')
使用分隔符为空格的拆分函数拆分句子并存储在templist中
templist = sentence.split(" ")
迭代templist中的单词,并将每个单词附加到单词列表中
for x in templist:
words.append(x)
您正在将一个列表传递给“words”(已经是一个列表)。您可以执行以下两项操作之一:
- 用法:
words=句子。拆分(“”)
- 如果以后要添加更多条目,并且要使用extend函数,请使用:
words=[]
words.extend(句子分割(“”)
希望这有帮助。您正在将一个列表传递给“单词”(已经是一个列表)。您可以执行以下两项操作之一:
- 用法:
words=句子。拆分(“”)
- 如果以后要添加更多条目,并且要使用extend函数,请使用:
words=[]
words.extend(句子分割(“”)
希望这有帮助。试试这个
words = []
def split(sentence):
words = sentence.split(" ")
return words
words = split("and the duck said: Woof")
print(words)
代码是非常自解释的,但为了完成:
我做了一个叫做单词的数组
我做了一个函数,可以为我们拆分一个句子
我调用该函数并将返回的内容用文字表示
输出是这样的
['和','鸭子','说:','汪']
试试这个
words = []
def split(sentence):
words = sentence.split(" ")
return words
words = split("and the duck said: Woof")
print(words)
代码是非常自解释的,但为了完成:
我做了一个叫做单词的数组
我做了一个函数,可以为我们拆分一个句子
我调用该函数并将返回的内容用文字表示
输出是这样的
['和','鸭子','说:','汪']
初始化单词的两行是冗余的。为什么不仅仅是单词=句子。拆分(“”
?单词=句子。拆分()
(无”
)或任何额外的括号)。初始化单词的两行是冗余的。为什么不干脆单词=句子。拆分(“”
?单词=句子。拆分()
(没有”
或任何额外的括号)。