Format and print list of tuples as one line - python

I have a list containing tuples that is generated from a database query and it looks something like this.
[(item1, value1), (item2, value2), (item3, value3),...]
The tuple will be mixed length and when I print the output it will look like this.
item1=value1, item2=value2, item3=value3,...
I have looked for a while to try to find a solution and none of the .join() solutions I have found work for this type of situation.

You're after something like:
>>> a = [('val', 1), ('val2', 2), ('val3', 3)]
>>> ', '.join('{}={}'.format(*el) for el in a)
'val=1, val2=2, val3=3'
This also doesn't care what type the tuple elements are... you'll get the str representation of them automatically.

You can use itertools as well
from itertools import starmap
', '.join(starmap('{}={}'.format, a))

If each tuple is only an (item, value) pair then this should work:
l = [(item1, value1), (item2, value2), (item3, value3), ...]
', '.join('='.join(t) for t in l)
'item1=value1, item2=value2, item3=value3, ...'

Try this:
lst = [('item1', 'value1'), ('item2', 'value2'), ('item3', 'value3')]
print ', '.join(str(x) + '=' + str(y) for x, y in lst)
I'm explicitly converting to string the items and values, if one (or both) are already strings you can remove the corresponding str() conversion:
print ', '.join(x + '=' + y for x, y in lst)

One possible solution is this, definitely the shortest code
>>> a = [('val', 1), ('val2', 2), ('val3', 3)]
>>>', '.join('%s=%s' % v for v in a)
'val=1, val2=2, val3=3'
works with python 2.7 as well

If you want something like that, I would use a dictionary.
dict = {1:2,3:4}
print dict
Then, you can loop through it like this:
dict = {1:2,3:3}
print dict
for i in dict:
print i, "=", dict[i]
Hope it helps!

Related

How can I sort a list based on a float inside each string in Python?

I am trying to figure out how to sort a list based on a certain part of each string. How do I write the key?
myKey(e)
return e[-5,-2]
print(sorted(["A: (" + str(round(7.24856, 2)) + ")", "B: (" + str(round(5.8333, 2)) + ")"], key = myKey))
I want the output to look like this: ['B: (5.83)', 'A: (7.25)']
In my full code, there are more than two strings in the list, so I cannot just sort them reversed alphabetically.
Thank you
Your syntax for function myKey is wrong. Other than that, you have to slice out the number in the string with the correct index (from index of char '(' + 1 to the character before the last) and convert them to floating point number value so that the sorted function can work properly.
def myKey(e):
return float(e[e.index('(')+1:-1])
print(sorted(["A: (" + str(round(7.24856, 2)) + ")", "B: (" + str(round(5.8333, 2)) + ")"], key = myKey))
You can use tuples sorted() to sort your data alongside with some list and string expressions to get the desired output:
input_list = ['A:(100.27)', 'B:(2.36)', 'C:(75.96)', 'D:(55.78)']
tuples_list = [(e.split(':(')[0], float(e.split(':(')[1][:-1])) for e in input_list]
sorted_tuples = sorted(tuples_list, key=lambda x: x[1])
result = [x[0] +':('+ str(x[1]) +')' for x in sorted_tuples]
print(input_list)
print(tuples_list)
print(sorted_tuples)
print(result)
Output:
['A:(100.27)', 'B:(2.36)', 'C:(75.96)', 'D:(55.78)']
[('A', 100.27), ('B', 2.36), ('C', 75.96), ('D', 55.78)]
[('B', 2.36), ('D', 55.78), ('C', 75.96), ('A', 100.27)]
['B:(2.36)', 'D:(55.78)', 'C:(75.96)', 'A:(100.27)']

Append length of string for each string in list

Input
strlist = ['test', 'string']
Desired output:
strlist = [('test', 4), ('string', 6)]
Attempt 1:
def add_len(strlist):
for i, c in enumerate(strlist):
strlist += str(len(strlist))
return strlist
Attempt 2:
def add_len(strlist):
for c in strlist:
c += " " + str(len(c))
return strlist
I realise I have the following issues:
Attempt 1: This results in an infinite loop, as the code keeps adding onto the list.
Attempt 2: This does not add the value to the string, however, when I do, I get the infinite loop issue from #1.
I believe I need to evaluate the number of elements in the list first and implement a while statement, but not quite sure how to do this.
Use a list comprehension:
strlist = ['test', 'string']
def add_len(strlist):
return [(s, len(s)) for s in strlist]
You can use a list comprehension like this.
def add_len(strlist):
return [(s, len(s)) for s in strlist]
Or expanded,
def add_len(strlist):
new_list = []
for s in strlist:
new_list.append((s, len(s)))
return new_list
In the expanded form we can see the steps it's going through a bit more clearly.
Create list new_list to put your strings and lengths into.
Iterate over each string in strlist.
For each string, append the string and its length to new_list.
Return new_list.
Of course, both of these gives you your desired output:
[('test', 4), ('string', 6)]
Using map():
>>> strlist
['test', 'string']
>>> list(map(lambda x: (x, len(x)), strlist))
[('test', 4), ('string', 6)]
for i, c in enumerate(strlist)
The i is the index of the element in the string list, and the c the value of the element. And you keep on appending the results in place (strlist), so that the strlist keeps growing.
While the second attempt won't output your desired results. The result will be strlist = ['test 4', 'string 6']. Every single element is not made up of tuple.
Meanwhile both the two attempts modify strlist in place, which will bring in potential issues (affect other attributes/parameters that refer to strlist).
A better solution for this is using list comprehension.
strlist = ['test', 'string']
new_strlist = [(s, len(s)) for s in strlist]

How to unpack tupled list in python

I have tupled list like this.
[('"ram', '18"'), ('"kp', '12"'), ('"nm', '14"')]
How to unpack this to get the result like below.
ram,18
kp,12
nm,14
Thanks.
You can just iterate over the list to unpack each piece.
mylist = [('"ram', '18"'), ('"kp', '12"'), ('"nm', '14"')]
for tup in mylist:
print ",".join(tup)
Output:
"ram,18"
"kp,12"
"nm,14"
If you do not like the quotes, just remove them after the join.
for tup in mylist:
print ",".join(tup).replace('"','')
Output:
ram,18
kp,12
nm,14
ta = [('"ram', '18"'), ('"kp', '12"'), ('"nm', '14"')]
for t in ta:
print ','.join(t)
or you can access individual items by indexing them:
ta[1]
Using a simple for loop should be enough.
Eg:
items = [('ram', '18'), ('kp', '12'), ('nm', '14')]
for label, value in items:
print label + "," + value

convert a list of strings that i would like to convert to a list of tuples

i have a list of strings that i would like to convert to a list of tuples. Below is an example.
['(0, "ass\'")', "(-1, '\\n print self.amount')", "(0, '\\n\\n ')"]
to be converted to.
[(0, "ass\'"), (-1, '\\n print self.amount'), (0, '\\n\\n ')]
any ideas?
[ast.literal_eval(x) for x in L]
map(ast.literal_eval, list_of_tuple_strings)
Unlike eval, ast.literal_eval will only evaluate literals, not function calls, so it much more secure.
The function eval is what you need I think, but be careful with its use:
>>> l = ['(0, "ass\'")', "(-1, '\\n print self.amount')", "(0, '\\n\\n ')"]
>>> map(eval, l)
[(0, "ass'"), (-1, '\n print self.amount'), (0, '\n\n ')]

split a string into a list of tuples

If i have a string like:
"user1:type1,user2:type2,user3:type3"
and I want to convert this to a list of tuples like so:
[('user1','type1'),('user2','type2'),('user3','type3')]
how would i go about doing this? I'm fairly new to python but couldn't find a good example in the documentation to do this.
Thanks!
>>> s = "user1:type1,user2:type2,user3:type3"
>>> [tuple(x.split(':')) for x in s.split(',')]
[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]
The cleanest way is two splits with a list comprehension:
str = "user1:type1,user2:type2,user3:type3"
res = [tuple(x.split(":")) for x in str.split(",")]
>>> s = "user1:type1,user2:type2,user3:type3"
>>> l = [tuple(user.split(":")) for user in s.split(",")]
>>> l
[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]
>>>
:)
If you want to do it without for loops, you can use map and lambda:
map(lambda x: tuple(x.split(":")), yourString.split(","))
Use the split function twice.
Try this for an example:
s = "user1:type1,user2:type2,user3:type3"
print [i.split(':') for i in s.split(',')]

Categories

Resources