问题
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 listl
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