How can I get around declaring an unused variable in a for loop?

后端 未结 10 1231
自闭症患者
自闭症患者 2020-11-27 16:03

If I have a list comprehension (for example) like this:

[\'\' for x in myList]

Effectively making a new list that has an empty string for e

10条回答
  •  难免孤独
    2020-11-27 17:00

    A verbose way is:

    newList = []
    while len(newList) < len(mylist):
        newList.append('')
    

    You avoid declaring an used variable this way.

    Also you can append both mutable and immutable objects (like dictionaries) into newList.

    Another thing for python newbies like me, '_', 'dummy' are a bit disconcerting.

提交回复
热议问题