【发布时间】:2020-01-03 16:22:08
【问题描述】:
我必须制作一个带有输入的字典,其中可能包含“key -> value1, value2”或“key -> key”。 键总是字符串,值总是整数,用逗号和空格分隔。 如果给定一个键和值,我必须将值存储到给定的键中。 如果密钥已经存在,我必须将给定的值添加到旧的值中。 如果给定一个键和另一个键,我必须将另一个键的值复制到第一个键。 如果其他键不存在,则必须忽略此输入行。 当我收到“end”命令时,我必须停止读取输入行,并且必须打印所有键及其值,格式如下: {key} === {value1, value2, value3}
data = input()
dict_ref = {}
def is_int(s):
try:
int(s)
return True
except ValueError:
return False
while data != "end":
list_data = data.split(" -> ")
name = list_data[0]
values = list_data[1].split(", ")
if name not in dict_ref and is_int(values[0]):
dict_ref[name] = values
elif values[0] in dict_ref:
dict_ref[name] = dict_ref[values[0]]
elif name in dict_ref and is_int(values[0]):
dict_ref[name].extend(values)
data = input()
for item in dict_ref:
print(f"{item} === ", end="")
print(", ".join(dict_ref[item]))
输入:
彼得 -> 1, 2, 3
艾萨克 -> 彼得
彼得 -> 4, 5
结束
预期输出:
彼得 === 1、2、3、4、5
Isacc === 1、2、3
实际输出:
彼得 === 1、2、3、4、5
Isacc === 1、2、3、4、5
【问题讨论】:
-
“预期输出” 用什么输入?在您的示例输入中,我既看不到 Peter 也看不到 Isaac。
-
对不起,我加了。
标签: python dictionary copy extend