在python中比较列表中的元素和字典 #/垃圾桶/蟒蛇3 导入系统 n=int(sys.stdin.readline()) dict={} 对于范围(n)中的i: str1=sys.stdin.readline() 键,值=str1.split(“”) dict[键]=值 字符串1=[] 尽管如此: check=sys.stdin.readline() 如果检查=“\n”: string1.追加(检查) 其他: 打破 对于string1中的i: 对于键,dict.items()中的值: 如果i==key:
按照我的理解,这将实现你想要的在python中比较列表中的元素和字典 #/垃圾桶/蟒蛇3 导入系统 n=int(sys.stdin.readline()) dict={} 对于范围(n)中的i: str1=sys.stdin.readline() 键,值=str1.split(“”) dict[键]=值 字符串1=[] 尽管如此: check=sys.stdin.readline() 如果检查=“\n”: string1.追加(检查) 其他: 打破 对于string1中的i: 对于键,dict.items()中的值: 如果i==key:,python,Python,按照我的理解,这将实现你想要的 #!/bin/python3 import sys n=int(sys.stdin.readline()) dicti={} for i in range(n): str1=sys.stdin.readline() key,value=str1.split(" ") dicti[key]=value string1=[] while True: check=sys.stdin.readline() if check!=
#!/bin/python3
import sys
n=int(sys.stdin.readline())
dicti={}
for i in range(n):
str1=sys.stdin.readline()
key,value=str1.split(" ")
dicti[key]=value
string1=[]
while True:
check=sys.stdin.readline()
if check!="\n":
string1.append(check)
else:
break
for i in string1:
for key,value in dicti.items():
if i==key: <-- comparison fails!!
sys.stdout.write(i)
它给出以下输出:
n = int(input("Enter the number of key value pairs in dictionary."))
dicti = {}
for i in range(n):
key, value = input("Enter the pair\t").split()
dicti[key] = value
string1 = []
while True:
check = input()
if check != "": # takes input till empty string
string1.append(check)
else:
break
l = []
for i in string1:
for key, value in dicti.items():
if i == key:
l.append(i)
print("For following values i equals key :", *l)
“for i in string1”将为您提供每个字符,请尝试“for i in string1.split(“”)您得到的错误是什么?细节:1-通过打印检查键的值。2.在打印时检查i的值。这必须足够细节让您知道发生了什么错误。@SarthakGupta否,string1是一个列表。无论如何,它将给出以下错误。对于string1中的i。拆分(“”):AttributeError:'list'对象没有属性'split'@YOLO我的错误是i==键比较对同一个值无效。
Enter the number of key value pairs in dictionary.3
Enter the pair 1 2
Enter the pair 2 3
Enter the pair 3 4
1
2
For following values i equals key : 1 2
Process finished with exit code 0