why * used before declaring a variable in python [duplicate]

邮差的信 提交于 2021-02-16 14:05:12

问题


I just started to learn python. I was following an example where they have used * before declaring a variable. My question is that what is the purpose of using this. Example, I am following

for i in range(n):
  name, *l = input().split()
  s = list(map(float, l))
  a[name] = s

After printing the variable I get a dictionary, which is made by a. But can't understand why * used before l variable


回答1:


It's a new unpacking feature introducted in python 3 called star unpacking or extended iterable unpacking.

when you do

name, *l = input().split()

the result of split is divided in 2 parts:

  • name gets the first element of the list
  • l gets the rest of the list (the floats)

so suppose you have a line like this:

name 0.0 1.0 2.0 3.0

split sets name to "name", and l takes ["0.0", "1.0", "2.0", "3.0"]. l is converted to a list of floats by list(map(float ...

Then name is used as a key and the list of floats as values.

Aside: your loop can be summarized in a dictionary comprehension like below:

a = {name:list(map(float,l)) for name, *l in (input().split() for _ in range(n))}


来源:https://stackoverflow.com/questions/45062375/why-used-before-declaring-a-variable-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!