Python using enumerate inside list comprehension

后端 未结 7 2296
滥情空心
滥情空心 2020-11-28 01:49

Lets suppose I have a list like this:

mylist = [\"a\",\"b\",\"c\",\"d\"]

To get the values printed along with their index I can use Python\

7条回答
  •  无人及你
    2020-11-28 02:08

    If you're using long lists, it appears the list comprehension's faster, not to mention more readable.

    ~$ python -mtimeit -s"mylist = ['a','b','c','d']" "list(enumerate(mylist))"
    1000000 loops, best of 3: 1.61 usec per loop
    ~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[(i, j) for i, j in enumerate(mylist)]"
    1000000 loops, best of 3: 0.978 usec per loop
    ~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[t for t in enumerate(mylist)]"
    1000000 loops, best of 3: 0.767 usec per loop
    

提交回复
热议问题