Home  >  Q&A  >  body text

What does Python mean? The syntax is a bit strange?

filelist = [x for x in os.listdir() if os.path.isfile(x)]
怪我咯怪我咯2676 days ago681

reply all(4)I'll reply

  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-22 11:54:31

    Equivalent to:

    filelist = []
    for x in os.listdir():
        if os.path.isfile(x):
            filelist.append(x)
        

    This is the content of list parsing.

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-22 11:54:31

    List generation
    is equivalent to. os.listdir() requires a parameter, which path you want to get the list.

    
    In [54]: filelist = []
    
    In [55]: for x in os.listdir("."):
        ...:     if os.path.isfile(x):
        ...:         filelist.append(x)
        ...:
    
    In [56]:
    

    Using list generation is a little faster than [].append(). You can test it using large batches. Why fast. The mechanism of the python listobject model is related. If you have time, you can read the python source code, which is written in C language

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-22 11:54:31

    Definition:
    List comprehensions (also known as list comprehensions) provide a concise and concise way to create lists.

    Specification:
    variable = [out_exp for out_exp in input_list if out_exp == 2]

    Example:
    multiples = [i for i in range(30) if i % 3 is 0]
    print(multiples)

    Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

    Scenario:
    When the logic in the loop is relatively simple, it can be replaced by derivation to increase code readability and cleanliness

    reply
    0
  • 为情所困

    为情所困2017-06-22 11:54:31

    List comprehensions
    List generation

    The order is as follows:

    reply
    0
  • Cancelreply