Python/Django: Creating a simpler list from values_list()

后端 未结 4 1751
深忆病人
深忆病人 2020-12-25 11:24

Consider:

>>>jr.operators.values_list(\'id\')
[(1,), (2,), (3,)]

How does one simplify further to:

[\'1\', \'2\',          


        
相关标签:
4条回答
  • 2020-12-25 11:55

    Something like this?

    x = [(1,), (2,), (3,)]
    y = [str(i[0]) for i in x]
    ['1', '2', '3']
    
    0 讨论(0)
  • 2020-12-25 12:06

    You need to do ..to get this output ['1', '2', '3']

    map(str, Entry.objects.values_list('id', flat=True).order_by('id'))

    0 讨论(0)
  • 2020-12-25 12:09

    You can use a list comprehension:

        >>> mylist = [(1,), (2,), (3,)]
        >>> [str(x[0]) for x in mylist]
        ['1', '2', '3']
    
    0 讨论(0)
  • 2020-12-25 12:11

    Use the flat=True construct of the django queryset: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_list

    From the example in the docs:

    >>> Entry.objects.values_list('id', flat=True).order_by('id')
    [1, 2, 3, ...]
    
    0 讨论(0)
提交回复
热议问题