Reputation: 603
I am trying to write a function that returns a string that looks like this (2,3|5,6|8,9), but my function on returns a blank string
numbers = [(4,5,6),(1,2,3),(7,8,9)]
def get_numbers(x):
mystring = ""
x = sorted(x)
for n in x:
if mystring is not "":
mystring+="|"
mystring+",".join(str(z) for z in n[1:])
return mystring
How can I fix this?
Upvotes: 0
Views: 174
Reputation: 8437
just for fun, a ugly one liner ;-)
'(' + '|'.join([','.join(map(str, l[1:])) for l in numbers]) + ')'
I also added the brackets as you wrote that you want a string looking like this.
Upvotes: 0
Reputation: 2817
Use join for change list and tuple to string
values = map(lambda x: x[1:], sorted(numbers))
print "|".join([",".join(map(str, value)) for value in values])
Upvotes: 1
Reputation: 3510
There's a tiny bug. You typed mystring=
instead of mystring +=
numbers = [(4,5,6),(1,2,3),(7,8,9)]
def get_numbers(x):
mystring = ""
x = sorted(x)
for n in x:
if mystring is not "":
mystring+="|"
mystring+=",".join(str(z) for z in n[1:])
return mystring
Upvotes: 2