繁体   English   中英

我在 python 中写的程序有什么问题?

[英]What is wrong with the program I have written in python?

问题描述是编写一个程序来获取字典中元素的键和值的输入。

以 python 字典格式显示键值对,求字典长度。

测试用例 1:

输入

3

23

33

43

32

33

34

OUTPUT

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))

对于上面给出的相同输入,我得到的 output 是:

The dictionary is

{23: 33, 43: 32, 33: 34}

Length of dictionary is

3

我的错误是什么?

看起来提供的输入按以下顺序排列:i)字典的大小 ii)键 iii)值

您似乎将其解读为键、值、键值...

提供的输入按以下顺序排列:

  1. 字典的大小
  2. 按键
  3. 价值

所以你的代码应该看起来更像这样:

# 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)}")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM