代码
text = ["300000", "300001", "500000", "500001"]
cnt = 0
for line in f:
if text in line:
print(line.strip())
cnt += 1
if cnt:
print(cnt, "count")
else:
print(text, "No data.")
错误:
Traceback (most recent call last):
File "C:/Users/users/PycharmProjects/Mining/Test Folder/Test2.py", line 10, in <module>
if text in line:
TypeError: 'in <string>' requires string as left operand, not list
为什么会出现此错误?
答案 0 :(得分:0)
in
关键字用于检查集合中是否有某个值。
如果您想知道line
是否在列表text
中,请切换操作数:
text = ["300000", "300001", "500000", "500001"]
cnt = 0
for line in f:
if line in text:
print(line.strip())
如果您想知道列表text
中的任何字符串是否在line
的内部/子字符串中:
text = ["300000", "300001", "500000", "500001"]
cnt = 0
for line in f:
if any([i in line for i in text]):
print(line.strip())
答案 1 :(得分:-1)
您需要了解python中“ in”的工作方式。
示例:
> "abc" in ["pqr", "xyz", "abc"]
True
在这里,我正在测试字符串'abc'是否在'in'右侧提到的列表中存在,该列表为[“ pqr”,“ xyz”,“ abc”]
但是您正在检查另一个列表(代码中的text
)中是否存在列表(代码中的line
)。
因此,如错误所示:“ in需要字符串作为左操作数”,但您提供了一个列表。