python中的元组转换到列表

时间:2018-07-25 20:31:25

标签: python list-comprehension

我有一个类似的元组

a = (1,2,3,4). 

是否可以将元组更改为

a = [('roll', 1),('roll',2),('roll', 3),('roll', 4)]

5 个答案:

答案 0 :(得分:3)

这里的列表理解很简单-

string sb = "Invoice #:" +
                "1267" +
                "<br>" +
                "Date:" +
                "4/16/2018 10:44:00 AM" +
                "<br>" +
                "PO #:" +
                "<br>" +
                "Reference:" +
                "<br>" +
                "Countermen:" +
                "A/A";

var matches = Regex.Match(sb,
    @"Invoice #:\s*(.*?)\s*<br>\s*Date:\s*(.*?)\s*<br>\s*PO #:\s*(.*?)\s*<br>\s*Reference:\s*(.*?)\s*<br>\s*Countermen:\s*(.*?)\s*$");

if (!matches.Success)
{
    throw new Exception("Unable to parse");
}

var invoice = matches.Groups[1].Value;
var date = matches.Groups[2].Value;

OP

a = [("roll", i) for i in a]

有关列表理解here

的更多信息

答案 1 :(得分:3)

-只需执行list comprehension

CREATE FUNCTION ... AS

请注意,这样做会重新绑定 a = [('roll', i) for i in a] ! (请参阅@ShadowRanger的注释。)

答案 2 :(得分:1)

轻松。使用a list comprehension

a = [("roll", x) for x in a]

with itertools stuff

import itertools

a = list(zip(itertools.repeat('roll'), a))  # No need to wrap in list if you'll iterate the result and discard it

答案 3 :(得分:0)

您还可以使用map函数:

i = (1,2,3,4)
list(map(lambda x: ('roll',x), i))

答案 4 :(得分:0)

或使用list()的另一种选择

 list(zip(["roll"]*4, a))