【问题标题】:Why does it add two strings instead of one?为什么它添加两个字符串而不是一个?
【发布时间】:2021-02-22 16:28:52
【问题描述】:

这是我的源代码:

destinations={"",}
destinations.discard("")
flightterminals={"Terminal 1":[],"Terminal 2":[], "Terminal 3":[]}
proceed="yes"
count=0
flightnumber=int(input("How many flights do you want to add: "))

for i in range(flightnumber):
  count+=1
  print("Where is plane {} headed?".format(count))
  temp=input("")+"1"
  destinations.add(temp[:-1])
  while ((temp in flightterminals["Terminal 1"]) or (temp in flightterminals["Terminal 2"]) or (temp in flightterminals["Terminal 3"])):
    temp=temp[:-1]+str(int(temp[-1])+1)
  print(type(temp))
  print(temp)
  flightterminals["Terminal {}".format((count-1)%3+1)]+=temp

print(flightterminals["Terminal 1"])

这是终端:

Flight Terminal Manager 5600
How many flights do you want to add: 1
Where is plane 1 headed?
x
<class 'str'>
x1
['x', '1']

倒数第三行 flightterminals["Terminal {}".format((count-1)%3+1)]+=temp 似乎将两个字符串添加到我的字典中的一个集合中,尽管 temp 在前一行中显示为只是一个字符串。我做错了什么?

【问题讨论】:

    标签: string dictionary set


    【解决方案1】:

    字典中的元素是列表。在您正在谈论的行中,您正在使用 += 运算符。因此,temp 被视为一个列表,其元素被推到字典中相应列表的末尾。你必须使用append()flightterminals["Terminal {}".format((count-1)%3+1)].append(temp)

    【讨论】:

    • 为了澄清,我在谈论为什么它打印出两个字符串而不是一个。如果我输入x,它应该打印x1,而不是1, x
    • 这就是我解释的。 value 包含 [x,1]。因此,print(", ".join(sorted(value))) 输出 1, x 而不是 x1 如预期的那样。
    • 我编辑了问题以澄清问题。请再看一遍,谢谢!
    • 哦,明白了。字典中的元素是列表。在您正在谈论的行中,您正在使用 += 运算符。因此,temp 被视为一个列表,其元素被推到字典中相应列表的末尾。你必须使用append()flightterminals["Terminal {}".format((count-1)%3+1)].append(temp)
    • 谢谢。顺便说一句,如果你改变你的答案,我会把它作为接受的答案。
    猜你喜欢
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 2015-12-05
    相关资源
    最近更新 更多