Related
I have a list of values in this format:
['11111-11111','22222-22222','33333-33333']
How do I strip the values in the list so I only have the first 5 numbers of each value in the list?
Looking for:
['11111','22222','33333']
You can use a list comprehension and slice each element in your list:
In [16]:
l=['11111-11111','22222-22222','33333-33333']
[x[:5] for x in l]
Out[16]:
['11111', '22222', '33333']
a call to str.split would work too:
In [17]:
l=['11111-11111','22222-22222','33333-33333']
[x.split('-')[0] for x in l]
Out[17]:
['11111', '22222', '33333']
If you would like a very simple solution, it could be like that:
yourList = ['11111-11111','22222-22222','33333-33333']
newList = []
for item in yourList:
newList.append(item[:5])
print(newList)
The output is ['11111', '22222', '33333']
I have the following string:
my_str = "StemCells(16.53),Bcells(13.59),Monocytes(11.58),abTcells(10.05),Macrophages(9.69), gdTCells(9.49),StromalCells(9.36),DendriticCells(9.20),NKCells(7.81),Neutrophils(2.71)"
What I want to do is to transform them in to this tuple
[ ('StemCells', 16.530000000000001),
('Bcells', 13.59),
('Monocytes', 11.58),
('abTcells', 10.050000000000001),
('Macrophages', 9.6899999999999995),
('gdTCells', 9.4900000000000002),
('StromalCells', 9.3599999999999994),
('DendriticCells', 9.1999999999999993),
('NKCells', 7.8099999999999996),
('Neutrophils', 2.71)]
How can I do that conveniently in Python
my_str = "StemCells(16.53),Bcells(13.59),Monocytes(11.58),abTcells(10.05),Macrophages(9.69), gdTCells(9.49),StromalCells(9.36),DendriticCells(9.20),NKCells(7.81),Neutrophils(2.71)"
import re
stuff = re.findall(r'(\w+)\(([0-9.]+)\)',my_str)
stuff
Out[4]:
[('StemCells', '16.53'),
('Bcells', '13.59'),
('Monocytes', '11.58'),
('abTcells', '10.05'),
('Macrophages', '9.69'),
('gdTCells', '9.49'),
('StromalCells', '9.36'),
('DendriticCells', '9.20'),
('NKCells', '7.81'),
('Neutrophils', '2.71')]
That gets you most of the way there, then it's just a bit of type conversion
[(s,float(f)) for s,f in stuff]
Out[7]:
[('StemCells', 16.53),
('Bcells', 13.59),
('Monocytes', 11.58),
('abTcells', 10.05),
('Macrophages', 9.69),
('gdTCells', 9.49),
('StromalCells', 9.36),
('DendriticCells', 9.2),
('NKCells', 7.81),
('Neutrophils', 2.71)]
well simplest solution, without using regex:
my_str = "StemCells(16.53),Bcells(13.59),Monocytes(11.58),abTcells(10.05),Macrophages(9.69), gdTCells(9.49),StromalCells(9.36),DendriticCells(9.20),NKCells(7.81),Neutrophils(2.71)"
that_str = map(lambda s: s.rstrip(')').split('(') ,my_str.split(','))
that_str = map(lambda s: (s[0], float(s[1])), that_str)
>>> that_str
[('StemCells', 16.53), ('Bcells', 13.59), ('Monocytes', 11.58), ('abTcells', 10.05), ('Macrophages', 9.69), (' gdTCells', 9.49), ('StromalCells', 9.36), ('DendriticCells', 9.2), ('NKCells', 7.81), ('Neutrophils', 2.71)]
you could do the job in one pass, using an external function, instead of a lambda:
def build_tuple(s):
t = s.rstrip(')').split('(')
return (t[0], float(t[1]))
that_str = map(build_tuple, my_str.split(','))
How about:
>>> zip(re.findall(r'([a-zA-Z]+)',my_str), map(float, re.findall(r'([0-9.]+)',my_str)))
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!
i have a list and want it as a string with quotes
mylist = [1,2,3]
require O/P as
myString = "'1','2','3'"
i tried mystring = '\',\''.join(mylist)
it gave me result as
mystring = "1','2','3"
first and last quotes (') are missing
This seems to be the only solution so far that isn't a hack...
>>> mylist = [1,2,3]
>>> ','.join("'{0}'".format(x) for x in mylist)
"'1','2','3'"
This can also be written more compactly as:
>>> ','.join(map("'{0}'".format, mylist))
"'1','2','3'"
Or, using an f-string:
>>> mylist = [1,2,3]
>>> ','.join(f"'{x}'" for x in mylist)
"'1','2','3'"
>>> mylist = [1,2,3]
>>> str([str(x) for x in mylist]).strip("[]")
"'1','2','3'"
as a simple hack, why don't you..
mystring = "'%s'" %"','".join(mylist)
wrap the result of your commands in quotes?
you can do this as well
mylist = [1, 2, 3]
mystring = str(map(str, mylist)).strip("[]")
OR regular repr:
>>> l=[1,2,3]
>>> ','.join(repr(str(i)) for i in l)
"'1','2','3'"
>>>
What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c'] to 'a,b,c'? (The cases ['s'] and [] should be mapped to 's' and '', respectively.)
I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1], but also feeling somewhat unsatisfied.
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
'a,b,c,d'
This won't work if the list contains integers
And if the list contains non-string types (such as integers, floats, bools, None) then do:
my_string = ','.join(map(str, my_list))
Why the map/lambda magic? Doesn't this work?
>>> foo = ['a', 'b', 'c']
>>> print(','.join(foo))
a,b,c
>>> print(','.join([]))
>>> print(','.join(['a']))
a
In case if there are numbers in the list, you could use list comprehension:
>>> ','.join([str(x) for x in foo])
or a generator expression:
>>> ','.join(str(x) for x in foo)
",".join(l) will not work for all cases. I'd suggest using the csv module with StringIO
import StringIO
import csv
l = ['list','of','["""crazy"quotes"and\'',123,'other things']
line = StringIO.StringIO()
writer = csv.writer(line)
writer.writerow(l)
csvcontent = line.getvalue()
# 'list,of,"[""""""crazy""quotes""and\'",123,other things\r\n'
Here is a alternative solution in Python 3.0 which allows non-string list items:
>>> alist = ['a', 1, (2, 'b')]
a standard way
>>> ", ".join(map(str, alist))
"a, 1, (2, 'b')"
the alternative solution
>>> import io
>>> s = io.StringIO()
>>> print(*alist, file=s, sep=', ', end='')
>>> s.getvalue()
"a, 1, (2, 'b')"
NOTE: The space after comma is intentional.
#Peter Hoffmann
Using generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I'd expect generator expressions to be preferred to imap.
>>> l = [1, "foo", 4 ,"bar"]
>>> ",".join(str(bit) for bit in l)
'1,foo,4,bar'
Don't you just want:
",".join(l)
Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:
https://docs.python.org/library/csv.html
>>> my_list = ['A', '', '', 'D', 'E',]
>>> ",".join([str(i) for i in my_list if i])
'A,D,E'
my_list may contain any type of variables. This avoid the result 'A,,,D,E'.
l=['a', 1, 'b', 2]
print str(l)[1:-1]
Output: "'a', 1, 'b', 2"
#jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator
from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))
Here is an example with list
>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [i[0] for i in myList]))
>>> print "Output:", myList
Output: Apple,Orange
More Accurate:-
>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList]))
>>> print "Output:", myList
Output: Apple,Orange
Example 2:-
myList = ['Apple','Orange']
myList = ','.join(map(str, myList))
print "Output:", myList
Output: Apple,Orange
If you want to do the shortcut way :) :
','.join([str(word) for word in wordList])
But if you want to show off with logic :) :
wordList = ['USD', 'EUR', 'JPY', 'NZD', 'CHF', 'CAD']
stringText = ''
for word in wordList:
stringText += word + ','
stringText = stringText[:-2] # get rid of last comma
print(stringText)
Unless I'm missing something, ','.join(foo) should do what you're asking for.
>>> ','.join([''])
''
>>> ','.join(['s'])
's'
>>> ','.join(['a','b','c'])
'a,b,c'
(edit: and as jmanning2k points out,
','.join([str(x) for x in foo])
is safer and quite Pythonic, though the resulting string will be difficult to parse if the elements can contain commas -- at that point, you need the full power of the csv module, as Douglas points out in his answer.)
I would say the csv library is the only sensible option here, as it was built to cope with all csv use cases such as commas in a string, etc.
To output a list l to a .csv file:
import csv
with open('some.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(l) # this will output l as a single row.
It is also possible to use writer.writerows(iterable) to output multiple rows to csv.
This example is compatible with Python 3, as the other answer here used StringIO which is Python 2.
mmm also need for SQL is :
l = ["foo" , "baar" , 6]
where_clause = "..... IN ("+(','.join([ f"'{x}'" for x in l]))+")"
>> "..... IN ('foo','baar','6')"
enjoit
My two cents. I like simpler an one-line code in python:
>>> from itertools import imap, ifilter
>>> l = ['a', '', 'b', 1, None]
>>> ','.join(imap(str, ifilter(lambda x: x, l)))
a,b,1
>>> m = ['a', '', None]
>>> ','.join(imap(str, ifilter(lambda x: x, m)))
'a'
It's pythonic, works for strings, numbers, None and empty string. It's short and satisfies the requirements. If the list is not going to contain numbers, we can use this simpler variation:
>>> ','.join(ifilter(lambda x: x, l))
Also this solution doesn't create a new list, but uses an iterator, like #Peter Hoffmann pointed (thanks).