Difference between a list comprehension and a for loop

前端 未结 5 1952
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 08:57
n=input()
y=n.split()
a=([int(x) for x in y])
print(a)

output

python .\\input_into_list.py
1 2 3
[1, 2, 3]

The above

5条回答
  •  执念已碎
    2021-01-23 09:54

    The main difference is in appearance and runtime speed. List comprehension is shorter, easier to understand and faster in execution time.

    In your code if you want to make it same as list comprehension you need to append each element to the list:

    n=input()
    y=n.split()
    a=[]
    for x in y:
        a.append(int(x))
    print(a)
    

    this will give you the same result as list comprehension one. In addition n.split() method itself returning the input as a list of elements. So:

    n=input()
    y=n.split()
    print(y)
    

    this is the same as above one. Just a last comment, when you use list comprehension or another list assigning you don't need to wrap the element to the brackets like: ()

    n=input()
    y=n.split()
    a=[int(x) for x in y]
    print(a)
    

提交回复
热议问题