【问题标题】:Two Column Data Structure - Python两列数据结构 - Python
【发布时间】:2014-07-25 12:04:37
【问题描述】:

如果我有一个颜色列表,我该如何在循环中创建数据结构;

[(u'blue', ), (u'green', ), (u'black', )]

并且需要如下所示的数据结构(可能是 2 列列表);

(('blue', 'blue'),
('green', 'green'),
('black', 'black'))

另外,为什么(以及什么类型的变量)是我的颜色列表由以 u 为前缀并被 ' ' 包围的项目组成?当我尝试执行字符串操作时,它似乎没有将其识别为字符串的一部分。数据(实际上不是颜色!)来自对 SQL 数据库中列的 pyodbc 查询。

例如,如果我正在修改 colours_list 中的第一行(语法不正确)

row[2:]
print row

(u'ue', ) # output

谢谢!

【问题讨论】:

    标签: python sql list data-structures pyodbc


    【解决方案1】:

    使用生成器表达式和元组解包:

    >>> colors = [(u'blue', ), (u'green', ), (u'black', )]
    
    # If you want a tuple of 2-items tuples, use `tuple()` and generator expression
    >>> tuple((color, color) for color, in colors)
    ((u'blue', u'blue'), (u'green', u'green'), (u'black', u'black'))
    
    # If you want a list of 2-items tuples, use list comprehension
    >>> [(color, color) for color, in colors]
    [(u'blue', u'blue'), (u'green', u'green'), (u'black', u'black')]
    

    u'...' 是一个 unicode 字符串文字。 (见Unicode Strings

    使用str functionunicode.encode method,可以将unicode对象转换为str对象:

    >>> tuple((str(color), str(color)) for color, in colors)
    (('blue', 'blue'), ('green', 'green'), ('black', 'black'))
    >>> tuple((color.encode(), color.encode()) for color, in colors)
    (('blue', 'blue'), ('green', 'green'), ('black', 'black'))
    

    【讨论】:

    • 我的方法是将列表推导转换为元组。 res = tuple([(col, col) for col in x]) 使用生成器是一种更 Pythonic 的方式?
    • @zinjaai,使用生成器表达式,可以避免创建临时列表对象。
    • tupule() 不需要 3 个参数吗?
    • @MarkCorrigan,你的意思是tupletuple 只接受一个可选参数。 (任何可迭代对象)并返回元组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 2015-09-11
    • 2018-02-26
    • 1970-01-01
    相关资源
    最近更新 更多