Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join values of map in python

I have a map like:

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

To print that I am doing

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

However I only want the values and comma separated like:

I have tried

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

but got

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

and also

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

How to print result like

15, 14, 0, 1, 12, 6, 4, 2, 8, 13, 3, 7, 9, 10, 11, 5
like image 678
edgarmtze Avatar asked Feb 02 '14 22:02

edgarmtze


1 Answers

Firstly, iterate through the list and get only the second element (you can use list comprehension for shorthand). Then use ",".join(list) to get the desired output, see 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

or if you have them in tuples:

>>> 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'

Alternatively, you can skip the map(str,list) and cast the elements into string within the list comprehension

>>> ",".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'
like image 56
alvas Avatar answered Oct 30 '22 11:10

alvas