Python 创建给定字符串和给定词典中所有单词的列表
我正在使用Python中的一个字符串和一个字典,尝试循环遍历该字符串,以便创建一个单词列表,这些单词同时出现在字符串和字典的键中。我目前拥有的是:Python 创建给定字符串和给定词典中所有单词的列表,python,string,list,dictionary,Python,String,List,Dictionary,我正在使用Python中的一个字符串和一个字典,尝试循环遍历该字符串,以便创建一个单词列表,这些单词同时出现在字符串和字典的键中。我目前拥有的是: ## dictionary will be called "dict" below sentence = "is this is even really a sentence" wordsinboth = [] for w in sentence.split(): if w in dict: wordsinboth += w
## dictionary will be called "dict" below
sentence = "is this is even really a sentence"
wordsinboth = []
for w in sentence.split():
if w in dict:
wordsinboth += w
但是,这段代码不是返回一个按空格分割的单词列表,而是返回句子中每个字符的列表。
即使我尝试在循环之前创建拆分单词列表,也会发生同样的情况,如下所示:
sentence = "is this is even really a sentence"
wordsinboth = []
sent = sentence.split()
for w in sent:
if w in dict:
wordsinboth += w
我猜我不能指定“如果w在dict中”并且仍然被空格分割?有没有关于如何解决这个问题的建议 使用
append
而不是+=
:
sentence = "is this is even really a sentence"
wordsinboth = []
for w in sentence.split():
if w in dict:
wordsinboth.append(w)
+=
运算符的工作方式与预期不同:
a = []
myString = "hello"
a.append(myString)
print(a) # ['hello']
b = []
b += myString
print(b) # ['h', 'e', 'l', 'l', 'o']
如果您对这种情况发生的原因感兴趣,请阅读以下问题:
另外,请注意,使用列表理解可能会为您的问题带来更优雅的解决方案:
wordsinboth = [word for word in sentence.split() if word in dict]
使用
append
代替+=
:
sentence = "is this is even really a sentence"
wordsinboth = []
for w in sentence.split():
if w in dict:
wordsinboth.append(w)
+=
运算符的工作方式与预期不同:
a = []
myString = "hello"
a.append(myString)
print(a) # ['hello']
b = []
b += myString
print(b) # ['h', 'e', 'l', 'l', 'o']
如果您对这种情况发生的原因感兴趣,请阅读以下问题:
另外,请注意,使用列表理解可能会为您的问题带来更优雅的解决方案:
wordsinboth = [word for word in sentence.split() if word in dict]
您可以在列表上使用
+=
,但必须向列表中添加列表,而不是值,否则值在添加之前会转换为列表。在您的例子中,w
字符串正在转换为其中所有字符的列表(例如'if'
=>['i','f']
)。要解决此问题,请通过在其周围添加[]
将该值添加到列表中:
for w in sentence.split():
if w in dict:
wordsinboth += [w]
您可以在列表上使用
+=
,但必须向列表中添加列表,而不是值,否则值在添加之前会转换为列表。在您的例子中,w
字符串正在转换为其中所有字符的列表(例如'if'
=>['i','f']
)。要解决此问题,请通过在其周围添加[]
将该值添加到列表中:
for w in sentence.split():
if w in dict:
wordsinboth += [w]
使用列表理解-这是一种更简单、更优雅的方式:
wordsinboth = [word for word in sentence.split() if w in dict]
循环中的问题是,您必须使用append
将新项添加到words
而不是+
运算符,请记住,它可能会创建重复项,如果您需要uniq项,您可以将结果包装到set
,从而提供uniq字
像这样:
wordsinboth = {word for word in sentence.split() if w in dict}
使用列表理解-这是一种更简单、更优雅的方式:
wordsinboth = [word for word in sentence.split() if w in dict]
循环中的问题是,您必须使用append
将新项添加到words
而不是+
运算符,请记住,它可能会创建重复项,如果您需要uniq项,您可以将结果包装到set
,从而提供uniq字
像这样:
wordsinboth = {word for word in sentence.split() if w in dict}