Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用元组列表连接字符串_Python - Fatal编程技术网

Python 用元组列表连接字符串

Python 用元组列表连接字符串,python,Python,需要有关将字符串对象与元组列表连接的帮助: 输入: 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' 我尝试了连接,但它与元组中的元素进行了叉积,如下所示: [ ['ABC | DEF | GHI|D1' 'ABC | DEF | GHI | 2.0'] ['ABC | DEF |

需要有关将字符串对象与元组列表连接的帮助:

输入:

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'
我尝试了连接,但它与元组中的元素进行了叉积,如下所示:

[
['ABC | DEF | GHI|D1'
'ABC | DEF | GHI | 2.0']
['ABC | DEF | GHI|D2'
'ABC | DEF | GHI | 3.0']
]
试试这个:

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

您可以使用模板,然后使用
格式

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

对于您拥有的字符串和元组,以下是一种简单易用的解决问题的方法

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])

结合使用
格式
和元组解包:

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