Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.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:对元组列表使用join()和map()_Python_Dictionary_Join_Tuples - Fatal编程技术网

Python:对元组列表使用join()和map()

Python:对元组列表使用join()和map(),python,dictionary,join,tuples,Python,Dictionary,Join,Tuples,我正在尝试合并元组列表,例如: test=[('X','X'),('O','O'),('X','X')] 进入 test\u merge=['XX','OO','XX'] 我从另一个人那里读到他/她使用: 映射(''.join,test) 得到: ['XX','OO','XX'] 所以我想尝试另一种方式: ''.join(映射(str,test)) 得到: ('X','X')('O','O')('X','X')) 我理解如果测试不是字符串列表,则不能使用'.join。但是,使用相同的map()和

我正在尝试合并元组列表,例如:
test=[('X','X'),('O','O'),('X','X')]
进入
test\u merge=['XX','OO','XX']

我从另一个人那里读到他/她使用:

映射(''.join,test)
得到:
['XX','OO','XX']

所以我想尝试另一种方式:

''.join(映射(str,test))
得到:
('X','X')('O','O')('X','X'))


我理解如果
测试
不是字符串列表,则不能使用
'.join
。但是,使用相同的map()和join(),为什么
map(“'join,test)
成功地将值合并到元组中?非常感谢

您可以这样做:

[''.join(x) for x in test]
map()
将iterable中的每个元素发送到给定函数。观察调用您尝试的每个函数时发生的情况:

>>> ''.join(('X', 'X'))
'XX'
>>> str(('X', 'X'))
"('X', 'X')"

如您所见,
'.join
使用空字符串分隔符连接所有传递的iterable参数,从而生成所需的结果<但是,code>str生成传递对象的字符串表示,如上所示,在本例中,它是一个
元组。它不会尝试对传递的对象执行任何其他类型的处理。

当我运行map('''.join,test)时,我得到['XX','OO','XX']。您的测试字符串中有输入错误吗?谢谢您指出。确实有一个拼写错误。我现在已经解决了。我想OP是在问他们为什么会得到这样的结果,而不是要求用其他方法来完成他们已经可以完成的任务(也没有解释)。嗨,TigerhawkT3,非常感谢你的澄清。昨晚我自己也经历了一个过程,现在一切都有意义了!