如何在python中加入map的值

我有一张地图:

0,15
1,14
2,0
3,1
4,12
5,6
6,4
7,2
8,8
9,13
10,3
11,7
12,9
13,10
14,11
15,5

打印我正在做的事情

def PrintValuesArray(su_array):
    for each in su_array:
        print ",".join(map(str, each))

但是我只希望将值和逗号分开,如:

我试过了

def PrintSuffixArray(su_array):
    for key, value in su_array:
        print ",".join(map(str, value))

但得到了

print “,”.join(map(str, value)) TypeError: argument 2 to map() must
support iteration

并且

def PrintSuffixArray(su_array):
    for key, value in su_array:
        print ",".join(map(str, value in su_array))

print “,”.join(map(str, value in su_array)) TypeError: argument 2 to
map() must support iteration

如何打印结果如

15, 14, 0, 1, 12, 6, 4, 2, 8, 13, 3, 7, 9, 10, 11, 5

最佳答案 首先,遍历列表并仅获取第二个元素(您可以使用
list comprehension作为速记).然后使用“,”.join(list)来获得所需的输出,请参阅
http://docs.python.org/2/library/string.html#string.join

>>> original = """0,15
... 1,14
... 2,0
... 3,1
... 4,12
... 5,6
... 6,4
... 7,2
... 8,8
... 9,13
... 10,3
... 11,7
... 12,9
... 13,10
... 14,11
... 15,5"""
>>> 
>>> print [i.split(",")[1] for i in original.split("\n")]
['15', '14', '0', '1', '12', '6', '4', '2', '8', '13', '3', '7', '9', '10', '11', '5']
>>> print ",".join([i.split(",")[1] for i in original.split("\n")])
15,14,0,1,12,6,4,2,8,13,3,7,9,10,11,5

或者如果你在元组中有它们:

>>> original = """0,15
... 1,14
... 2,0
... 3,1
... 4,12
... 5,6
... 6,4
... 7,2
... 8,8
... 9,13
... 10,3
... 11,7
... 12,9
... 13,10
... 14,11
... 15,5"""
>>>
>>> original_tuples = [tuple(i.split(",")) for i in original.split("\n")]
>>> original_tuples
[('0', '15'), ('1', '14'), ('2', '0'), ('3', '1'), ('4', '12'), ('5', '6'), ('6', '4'), ('7', '2'), ('8', '8'), ('9', '13'), ('10', '3'), ('11', '7'), ('12', '9'), ('13', '10'), ('14', '11'), ('15', '5')]
>>> ",".join(map(str,[j for i,j in original_tuples]))
'15,14,0,1,12,6,4,2,8,13,3,7,9,10,11,5'

或者,您可以跳过映射(str,list)并将元素转换为列表解析中的字符串

>>> ",".join(str(j) for i,j in original_tuples)
'15,14,0,1,12,6,4,2,8,13,3,7,9,10,11,5'
点赞