Printing using list comprehension

后端 未结 10 1689
一生所求
一生所求 2020-12-03 10:58

From my Python console

>>> numbers = [1,2,3]
>>> [print(x) for x in numbers]
1
2
3
[None, None, None]

Why does this print

相关标签:
10条回答
  • 2020-12-03 11:37

    If this behaviour of the Print function bothers, I suggest you don't use the Print function in the list comprehension, just use the following one-liner which is compact and more Pythonic:

    >>> [x for x in [1,2,3]]
    [1, 2, 3]
    
    0 讨论(0)
  • 2020-12-03 11:43

    A list comprehension is not the right tool for the job at hand. It'll always return a list, and given that print() evaluates to None, the list is filled with None values. A simple for loop works better when we're not interested in creating a list of values, only in evaluating a function with no returned value:

    for x in numbers:
        print(x)
    
    0 讨论(0)
  • 2020-12-03 11:47

    print is a function, it's just like

    >>>def f(x):
    ...:   pass
    >>>[f(x) for x in numbers]
    
    0 讨论(0)
  • 2020-12-03 11:47

    An ugly way of doing this is _=[print(i) for i in somelist] It does work but is not encouraged:)

    0 讨论(0)
  • 2020-12-03 11:50

    You can use the String Join() method and print the string. For example:

    >>> print('\n'.join(numbers))
    1
    2
    3
    >>> print(', '.join(numbers))
    1, 2, 3
    >>> print(',\n'.join(numbers))
    1,
    2,
    3
    
    0 讨论(0)
  • 2020-12-03 11:53

    List comprehensions always return a list.

    Based on this information, your print() statement must wrap the whole list comprehension argument:

    Numbers = [1, 2, 3]
    
    print([x for x in Numbers])
    

    If you want to print items of a list one by one, a for loop is more suitable for this matter.

    0 讨论(0)
提交回复
热议问题