从数据库获取的单个列表的元组转换为python中的列表

时间:2018-07-31 12:11:20

标签: python list tuples

    selectedTeam = str(self.comboBox_2.currentText())
    sql2="select Players from TeamFormed where Name='"+selectedTeam+"';"
    curt=Teams.cursor()
    curt.execute(sql2)
    players=curt.fetchone()
    #Just to check the type length and contents
    print(type(players))
    print(players)
    print(len(players))

    ast.literal_eval(players[0])

    #Just to check the type length and contents
    print(type(players))
    print(players)
    print(len(players))

我有一个这样的元组

("['Virat Kohli', 'A B de villiers', 'K L Rahul', 'Aron Finch', 'Glenn Maxwell', 'Suresh Raina', 'Shikhar Dhawan', 'Rohit Sharma', 'B Kumar', 'James Anderson', 'M Shami', 'Jasprit Bumrah']",)
从数据库中获取数据后生成的

。 该元组的长度显示为1。 我想将其转换为长度为12的列表。

2 个答案:

答案 0 :(得分:0)

您可以使用literal_eval

import ast
l = ("['Virat Kohli', 'A B de villiers', 'K L Rahul', 'Aron Finch', 'Glenn Maxwell', 'Suresh Raina', 'Shikhar Dhawan', 'Rohit Sharma', 'B Kumar', 'James Anderson', 'M Shami', 'Jasprit Bumrah']",)

k = ast.literal_eval(l[0])
# ['Virat Kohli', 'A B de villiers', 'K L Rahul', 'Aron Finch', 'Glenn Maxwell', 'Suresh Raina', 'Shikhar Dhawan', 'Rohit Sharma', 'B Kumar', 'James Anderson', 'M Shami', 'Jasprit Bumrah']
len(k) # 12

答案 1 :(得分:0)

这里:

a = ("['Virat Kohli', 'A B de villiers', 'K L Rahul', 'Aron Finch', 'Glenn Maxwell', 'Suresh Raina', 'Shikhar Dhawan', 'Rohit Sharma', 'B Kumar', 'James Anderson', 'M Shami', 'Jasprit Bumrah']",)
exec('b = ' + a[0])

for c in b:
    print(c)

编辑

或者使用@ᴀʀᴍᴀɴ的解决方案,我认为更好。