如何在Python中连接map的值

kd3sttzy  于 2023-08-02  发布在  Python
关注(0)|答案(5)|浏览(101)

我有一张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:map()的参数2必须支持迭代
而且

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:map()的参数2必须支持迭代
如何打印结果

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

z9gpfhce

z9gpfhce1#

首先,遍历列表并仅获取第二个元素(您可以使用列表解析来简化)。然后使用",".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'


或者,您可以跳过map(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'

n53p2ov0

n53p2ov02#

试试这个:

print ", ".join(str(y) for x, y in su_array)

字符串

zazmityj

zazmityj3#

你可以使用str.join()和list-comprehension:

>>> su_array = [(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([str(b) for _, b in su_array])
'15, 14, 0, 1, 12, 6, 4, 2, 8, 13, 3, 7, 9, 10, 11, 5'

字符串

wz3gfoph

wz3gfoph4#

>>> a = """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
... """
>>> map(lambda x: x.split(',')[1], a.split())
['15', '14', '0', '1', '12', '6', '4', '2', '8', '13', '3', '7', '9', '10', '11', '5']

字符串

dbf7pr2w

dbf7pr2w5#

如果我理解,从你的问题,根据你提到的输出,你有类似的东西

`su_array = [(1, 14), (2, 0), (3, 1), ...]` etc...

字符串
在此基础上,使用:

print(", ".join(str(a[1]) for a in su_array))


或者

print(", ".join(map(lambda a: str(a[1]), su_array)))


都能得到你想要的。

相关问题