A little knowledge of python basics ===* unpacking, formatted output and print

Features in python3:

>>> name = "botoo"
>>> print(f"my name is {name}")
my name is botoo

Equivalent to:

>>> print("my name is {}".format(name))
my name is botoo

 

Looking at the list again, if we want to print each content of a list, for example, I want to output the format of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

>>> L = list(range(10))
>>> for l in L:
    print(l)

    
0
1
2
3
4
5
6
7
8
9

Obviously not, so what I can think of is to change the end parameter of the print() function:

>>> for l in L:
    print(l, end=",")

    
0,1,2,3,4,5,6,7,8,9,

So got this answer, but with an extra comma at the end. This can be removed by code:

>>> for i in L:
    if i != L[-1]:
        print(i,end = ",")
    else:
        print(i)

        
0,1,2,3,4,5,6,7,8,9

So far we have found that the whole process is very cumbersome and complicated.

Is there an easier way, with more pythonic code

 

Based on this, I thought of the effect of using * to unpack function parameters a few days ago. The code is as follows:

>>> def func(a,b,c):
    print(a+b+c)

    
>>> arg = (1,2,3)
>>> func(*arg)
6

*将arg的每一项分配给了func函数,而这个过程中*的作用就是解包

于是,再次尝试:

>>> print(*L)
0 1 2 3 4 5 6 7 8 9

果然可行,再加入,号就可以成功。

>>> print(*L,sep = ",")
0,1,2,3,4,5,6,7,8,9

(关于print()函数的sep,和end参数的用法自行百度。)

 

当然,还有方法就是使用.join(),网上说明很多,故不再赘述。

print(",".join([str(i) for i in L]))
0,1,2,3,4,5,6,7,8,9

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325950365&siteId=291194637