我用python编写的程序有什么问题?
问题描述是编写一个程序来获取字典中元素的键和值的输入 以python字典格式显示键值对,并查找字典的长度 测试用例1: 输入 输出我用python编写的程序有什么问题?,python,dictionary,Python,Dictionary,问题描述是编写一个程序来获取字典中元素的键和值的输入 以python字典格式显示键值对,并查找字典的长度 测试用例1: 输入 输出 The dictionary is {23: 32, 33: 33, 43: 34} Length of dictionary is 3 我的代码是: n = int(input()) di = dict() for i in range(0, n): a = int(input()) b = int(input()) di[a] = b p
The dictionary is
{23: 32, 33: 33, 43: 34}
Length of dictionary is
3
我的代码是:
n = int(input())
di = dict()
for i in range(0, n):
a = int(input())
b = int(input())
di[a] = b
print("The dictionary is")
print(di)
print("Length of dictionary is")
print(len(di))
对于上面给出的相同输入,我得到的输出是:
The dictionary is
{23: 33, 43: 32, 33: 34}
Length of dictionary is
3
我的错误是什么?提供的输入似乎是按以下顺序进行的: i) 字典的大小 ii)钥匙 iii)价值观
您似乎将其理解为键、值、键值…提供的输入顺序如下:
# collecting length
n=int(input())
# creating lists for keys and values
keys_list = []
values_list = []
# collecting keys
for i in range(0,n):
a=int(input())
keys_list.append(a)
# collecting values
for i in range(0,n):
a=int(input())
values_list.append(a)
# creating dictionnary
di = dict(zip(keys_list, values_list))
# printing result
print("The dictionary is")
print(di)
print("Length of dictionary is")
print(len(di))
像这样,首先收集所有键并将它们放入列表,然后收集所有值并将它们放入列表。最后,您将从这两个列表中创建您的词汇表。也许简单地说:
n = int(input('Input len of dict: '))
j = 0
l = []
while j != n * 2:
l.append(input('input num: '))
j += 1
di = {int(x): int(x[::-1]) for x in l[:3] if x[::-1] in l}
print(f"The dictionary is {di}\nLength of dictionary is {len(di)}")
看起来字典是以键作为数字创建的,将数字作为值创建。可能您必须将所有值存储在一个列表中,然后创建字典。如果您找到一个回答您的问题的答案,请接受它
n = int(input('Input len of dict: '))
j = 0
l = []
while j != n * 2:
l.append(input('input num: '))
j += 1
di = {int(x): int(x[::-1]) for x in l[:3] if x[::-1] in l}
print(f"The dictionary is {di}\nLength of dictionary is {len(di)}")