为什么在这种情况下必须使用星号?

时间:2020-02-29 07:55:26

标签: python python-3.x python-3.7

由于我希望输入仅显示对象,动物,运动,为什么要添加一个星号使其* categories能够将类别过滤为对象,动物,运动并在此之后忽略其他任何单词?就像在这种情况下添加星号如何工作?

import random

# Store the category and values into a dictionary
categories = {
    "objects": ["tables", "ladders", "chairs"],
    "animals": ["chicken", "dog", "cat"],
    "sports": ["basketball", "soccer", "rugby"]

}

response = input(' One among the following [%s] : \n' % ', '.join(map(str, list((*categories,)))))

1 个答案:

答案 0 :(得分:1)

以下是细分:

import snoop

categories = {
    "objects": ["tables", "ladders", "chairs"],
    "animals": ["chicken", "dog", "cat"],
    "sports": ["basketball", "soccer", "rugby"]

}

snoop.pp.deep(lambda: ', '.join(map(str, list((*categories,)))))

输出:

................... categories = {'objects': ['tables', 'ladders', 'chairs'], 'animals': ['chicken', 'dog', 'cat'], 'sports': ['basketball', 'soccer', 'rugby']}
........... (*categories,) = ('objects', 'animals', 'sports')
....... list((*categories,)) = ['objects', 'animals', 'sports']
... map(str, list((*categories,))) = <map object at 0x10d261520>
', '.join(map(str, list((*categories,)))) = 'objects, animals, sports'

遍历字典会产生其密钥,因此(*categories,) = ('objects', 'animals', 'sports')

大多数代码都是毫无意义的:', '.join(categories)也可以正常工作。以下各项都是独立的冗余,可以省略:

  • map(str, ...)
  • list(...)
  • (*...,)