2016-10-25 47 views
1

的名单需要用连接字符串对象与元组的列表帮助:加入字符串元组

输入:

My_String = 'ABC | DEF | GHI' 
My_List = [('D1', 2.0), ('D2', 3.0)] 

产量预计:

'ABC | DEF | GHI | D1 | 2.0' 
'ABC | DEF | GHI | D2 | 3.0' 

我试过拼接,但它与元组中的元素进行交叉产品并且如下所示:

​​06913 210

回答

3

试试这个:

for name, value in My_List: 
    print(' | '.join((My_String, name, str(value)))) 
2

您可以使用一个模板,然后用format

My_String = 'ABC | DEF | GHI' 
My_List = [('D1', 2.0), ('D2', 3.0)] 

template = My_String + ' | {} | {}' 

for i,j in My_List: 
    print(template.format(i,j)) 

输出:

ABC | DEF | GHI | D1 | 2.0 
ABC | DEF | GHI | D2 | 3.0 
2

对于字符串和元组你,以下是一种简单易行的方法来解决你的问题

the_string = "ABC | DEF | GHI" 
the_list = [('D1', 2.0), ('D2', 3.0)] 
#you need to loop through the tuple to get access to the values in the tuple 
for i in the_list: 
    print the_string, " | "+ str(i[0])+" | "+ str(i[1]) 
0

使用的format的组合,以及元组拆包:

print map(lambda x: "{} | {} | {}".format(My_String, *x), My_List)