【问题标题】:How to make (list, dictionary) in Python [duplicate]如何在Python中制作(列表,字典)[重复]
【发布时间】:2015-07-29 03:23:35
【问题描述】:

如何制作(列表、字典)来自:

n = ('banana', 5, 'apple', 400, 'orange', 250, 'peach', 300)

到:

(fruit -> price)

例子:

for..print all
    banana -> 5
    apple -> 400
    orange -> 250
    peach -> 300

【问题讨论】:

  • 另外,OP,你的 n 不是一个列表,而是一个元组......
  • 怎么做?通过编写一些代码。
  • @Matthias : 你很聪明

标签: python dictionary


【解决方案1】:

您可以使用dictzip

n = ('banana', 5, 'apple', 400, 'orange', 250, 'peach', 300)

print(dict(zip(n[::2],n[1::2])))
{'orange': 250, 'peach': 300, 'banana': 5, 'apple': 400}

zip(n[::2],n[1::2]) 创建 [('banana', 5), ('apple', 400), ('orange', 250), ('peach', 300)] 然后在结果上调用 dict 从每个元组创建键/值对。

更有效地使用 iter 来避免切片和创建新列表:

n = ('banana', 5, 'apple', 400, 'orange', 250, 'peach', 300)
it = iter(n)
print(dict(zip(it,it)))

要打印项目:

for fruit, cost in dict(zip(it,it)).items():
    print("{} -> {}".format(fruit, cost))

apple -> 400
orange -> 250
banana -> 5
peach -> 300

如果你只想要成对的就用 zip:

for fruit, cost in zip(it,it):
    print("{} -> {}".format(fruit, cost))

banana -> 5
apple -> 400
orange -> 250
peach -> 300

dicts 没有顺序,这就是为什么输出在两者之间的顺序不同的原因。

【讨论】:

  • 谢谢你的回复,没有print我怎么做结构?
  • @croutreb,我不确定我是否理解,我添加了如何打印项目
猜你喜欢
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
  • 2016-01-10
  • 2021-11-02
  • 2016-02-26
  • 2020-03-03
相关资源
最近更新 更多