簡體   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