Python 无法在列表中找到已使用csv读取器读入的特定字符串?
我正在读一个单词列表(dict),试图找出列表中是否有一个特定的单词。代码如下:Python 无法在列表中找到已使用csv读取器读入的特定字符串?,python,python-3.x,Python,Python 3.x,我正在读一个单词列表(dict),试图找出列表中是否有一个特定的单词。代码如下: dict = [] with open('words.txt', newline='') as inputfile: for row in csv.reader(inputfile): dict.append(row) print('hello' in dict) 我知道hello在列表dict中,但最后一行代码返回False 如果我输入以下代码,
dict = []
with open('words.txt', newline='') as inputfile:
for row in csv.reader(inputfile):
dict.append(row)
print('hello' in dict)
我知道hello在列表dict中,但最后一行代码返回False
如果我输入以下代码,它将为真,因此它必须与如何读取它有关:
dict=['hel','hello','heo','sds','sdswe']
print('hello' in dict)
有什么想法吗?原因是您正在从
.txt
文件中附加列表,而不是字符串,最后是列表列表,而不是预期的字符串列表
csv.reader的作用是将.txt
文件的内容作为列表读取
例如,如果.txt文件
Your
Name
csv.reader将对其进行如下解释:
[['Your'], ['Name']]
因此是列表列表,而不是字符串列表
因此,如果需要字符串列表,可以这样做:
yourlist.append(row[0].strip()) #striping will remove the newline
这将为您提供行的元素,而不是列表本身。如果这对你有帮助,请告诉我
最后,这是您可以拥有的:
yourlist = []
with open('words.txt', newline='') as inputfile:
for row in csv.reader(inputfile):
yourlist.append(row[0].strip())
print('hello' in yourlist)
您的代码有两个主要问题:
lst
表示列表,而不是dict
行
返回一个列表,而您只需要每个行
实例中的第一个条目;i、 e.使用行[0]
print(type(row))
查看您正在使用的对象类型
import csv
from io import StringIO
csvstr = StringIO("""hel
hello
heo
sds
sdswe
""")
lst = []
for row in csv.reader(csvstr):
print(type(row)) # <class 'list'>
lst.append(row[0])
print('hello' in lst) # True
导入csv
从io导入StringIO
csvstr=StringIO(“”hel
你好
呵呵
十二烷基硫酸钠
sdswe
""")
lst=[]
对于csv.reader(csvstr)中的行:
打印(类型(行))#
lst.append(第[0]行)
打印('hello'在lst中)#正确
你为什么要称列表为dictX此代码覆盖内置的dict
,并为其分配一个列表。有点让人困惑。为什么不添加print(dict)
来查看它包含的内容呢?好的,所以我更新了代码,使用DictWB,这没有什么区别。它打印True
,因为“hello”在您的列表中。它可能会读为False
,因为row
是一个列表。干杯,这非常有用@很高兴我能帮上忙。欢迎来到这个家庭。