Howdy, I've got multiple lists. For example:
[u'This/ABC']
[u'is/ABC']
[u'not/ABC']
[u'even/ABC']
[u'close/ABC']
[u'to/ABC']
[u'funny/ABC']
[u'./ABC']
[u'O/ABC']
[u'noez/ABC']
[u'!/ABC']
I need to join this List to
This/ABC is/ABC not/ABC even/ABC close/ABC to/ABC funny/ABC ./ABC
O/ABC noez/ABC !/ABC
How do I do that please? Yes, with the empty space in between!
If you put them all in a list, for example like this:
a = [
[u'This/ABC'],
[u'is/ABC'],
...
]
You can get your result by adding all the lists and using a regular join on the result:
result = ' '.join(sum(a, []))
After re-reading the question a couple of times, I suppose you also want that empty line. This is just more of the same. Add:
b = [
[u'O/ABC'],
[u'HAI/ABC'],
...
]
lines = [a, b]
result = '\n\n'.join([' '.join(sum(line, [])) for line in lines])
To join lists, try the chain function in the module itertools, For example, you can try
import itertools
print ' '.join(itertools.chain(mylist))
if the new line between the two lists are intentional, then add '\n' at the end of the first list
import itertools
a = [[u'This/ABZ'], [u'is/ABZ'], ....]
b = [[u'O/ABZ'], [u'O/noez'], ...]
a.append('\n')
print ' '.join(itertools.chain(a + b))
Easy:
x = [[u'O/ABC'], [u'noez/ABC'], [u'!/ABC']]
print ' '.join(y[0] for y in x)
If you put all your lists in one list, you can do it like this:
' '.join(e[0] for e in [[u'This/ABC'], [u'is/ABC']])
Related
I have a list of strings that look like this:
['C04.123.123.123', 'C03.456.456.456', 'C05.789.789.789']
I'm trying to split each string so I get different backward combinations of splits on the period delimiter. Basically, if I only take the example of the first string, I want to get:
['C04.123.123.123', 'C04.123.123', 'C04.123', 'C04']
How can I achieve this? I've tried looking into itertools.combinations and the standard split features but no luck.
One-line, easy to understand (was less easy to tune :)), using str.rsplit with maxsplit gradually increasing up to the number of dots:
lst = ['C04.123.123.123', 'C03.456.456.456', 'C05.789.789.789']
result = [x.rsplit(".",i)[0] for x in lst for i in range(x.count(".")+1) ]
result:
['C04.123.123.123',
'C04.123.123',
'C04.123',
'C04',
'C03.456.456.456',
'C03.456.456',
'C03.456',
'C03',
'C05.789.789.789',
'C05.789.789',
'C05.789',
'C05']
The only thing that annoys me is that it calls split a lot just to keep the first element. Too bad there isn't a built-in lazy split function we could call next on.
You can use a list comprehension:
d = ['C04.123.123.123', 'C03.456.456.456', 'C05.789.789.789']
new_d = [a+('.' if i else '')+'.'.join(i) for a, *c in map(".".split, d)
for i in [c[:h] for h in range(len(c)+1)][::-1]]
Output:
['C04.123.123.123', 'C04.123.123', 'C04.123', 'C04', 'C03.456.456.456', 'C03.456.456', 'C03.456', 'C03', 'C05.789.789.789', 'C05.789.789', 'C05.789', 'C05']
start_list = ['C04.123.123.123', 'C03.456.456.456', 'C05.789.789.789']
final_list = []
for item in start_list:
broke_up = item.split('.')
temp = []
full_item = []
for sect in broke_up:
temp.append(sect)
full_item.append(".".join(temp))
final_list.extend(full_item)
print(final_list)
Alternatively you can final_list.append(full_item) to keep seperate lists for each string in the original list.
Try this:
list(accumulate(s.split('.'), lambda a, b: a + '.' + b))[::-1]
You can use itertools.accumulate:
from itertools import accumulate
s = 'C04.123.123.123'
# define the incremental step
append = lambda s, e: s + '.' + e
result = list(accumulate(s.split('.'), append))[::-1]
I would like to separate my string every both commas but I can not, can you help me.
This is what I want: ['nb1,nb2','nb3,nb4','nb5,nb6']
Here is what I did :
a= 'nb1,nb2,nb3,nb4,nb5,nb6'
compteur=0
for i in a:
if i==',' :
compteur+=1
if compteur%2==0:
print compteur
test = a.split(',', compteur%2==0 )
print a
print test
The result:
2
4
nb1,nb2,nb3,nb4,nb5,nb6
['nb1', 'nb2,nb3,nb4,nb5,nb6']
Thanks you by advances for you answers
You can use regex
In [12]: re.findall(r'([\w]+,[\w]+)', 'nb1,nb2,nb3,nb4,nb5,nb6')
Out[12]: ['nb1,nb2', 'nb3,nb4', 'nb5,nb6']
A quick fix could be to simply first separate the elements by commas and then join the elements by two together again. Like:
sub_result = a.split(',')
result = [','.join(sub_result[i:i+2]) for i in range(0,len(sub_result),2)]
This gives:
>>> result
['nb1,nb2', 'nb3,nb4', 'nb5,nb6']
This will also work if the number of elements is odd. For example:
>>> a = 'nb1,nb2,nb3,nb4,nb5,nb6,nb7'
>>> sub_result = a.split(',')
>>> result = [','.join(sub_result[i:i+2]) for i in range(0,len(sub_result),2)]
>>> result
['nb1,nb2', 'nb3,nb4', 'nb5,nb6', 'nb7']
You use a zip operation of the list with itself to create pairs:
a = 'nb1,nb2,nb3,nb4,nb5,nb6'
parts = a.split(',')
# parts = ['nb1', 'nb2', 'nb3', 'nb4', 'nb5', 'nb6']
pairs = list(zip(parts, parts[1:]))
# pairs = [('nb1', 'nb2'), ('nb2', 'nb3'), ('nb3', 'nb4'), ('nb4', 'nb5'), ('nb5', 'nb6')]
Now you can simply join every other pair again for your output:
list(map(','.join, pairs[::2]))
# ['nb1,nb2', 'nb3,nb4', 'nb5,nb6']
Split the string by comma first, then apply the common idiom to partition an interable into sub-sequences of length n (where n is 2 in your case) with zip.
>>> s = 'nb1,nb2,nb3,nb4,nb5,nb6'
>>> [','.join(x) for x in zip(*[iter(s.split(','))]*2)]
['nb1,nb2', 'nb3,nb4', 'nb5,nb6']
I want to make list data to string.
My list data like this :
[['data1'],['data2'],['data3']]
I want to convert to string like this :
"[data1] [data2] [data3]"
I try to use join like this :
data=[['data1'],['data2'],['data3']]
list=" ".join(data)
But get error like this :
string= " ".join(data)
TypeError: sequence item 0: expected string, list found
Can somebody help me?
Depending on how closely you want the output to conform to your sample, you have a few options, show here in ascending order of complexity:
>>> data=[['data1'],['data2'],['data3']]
>>> str(data)
"[['data1'], ['data2'], ['data3']]"
>>> ' '.join(map(str, data))
"['data1'] ['data2'] ['data3']"
>>> ' '.join(map(str, data)).replace("'", '')
'[data1] [data2] [data3]'
Keep in mind that, if your given sample of data doesn't match your actual data, these methods may or may not produce the desired results.
Have you tried?
data=[['data1'],['data2'],['data3']]
t = map(lambda x : str(x), data)
print(" ".join(t))
Live demo - https://repl.it/BOaS
In Python 3.x , the elements of the iterable for str.join() has to be a string .
The error you are getting - TypeError: sequence item 0: expected string, list found - is because the elements of the list you pass to str.join() is list (as data is a list of lists).
If you only have a single element per sublist, you can simply do -
" ".join(['[{}]'.format(x[0]) for x in data])
Demo -
>>> data=[['data1'],['data2'],['data3']]
>>> " ".join(['[{}]'.format(x[0]) for x in data])
'[data1] [data2] [data3]'
If the sublists can have multiple elements and in your output you want those multiple elements separated by a , . You can use a list comprehension inside str.join() to create a list of strings as you want. Example -
" ".join(['[{}]'.format(','.join(x)) for x in data])
For some other delimiter other than ',' , use that in - '<delimiter>'.join(x) .
Demo -
>>> data=[['data1'],['data2'],['data3']]
>>> " ".join(['[{}]'.format(','.join(x)) for x in data])
'[data1] [data2] [data3]'
For multiple elements in sublist -
>>> data=[['data1','data1.1'],['data2'],['data3','data3.1']]
>>> " ".join(['[{}]'.format(','.join(x)) for x in data])
'[data1,data1.1] [data2] [data3,data3.1]'
>>> import re
>>> l = [['data1'], ['data2'], ['data3']]
>>> s = ""
>>> for i in l:
s+= re.sub(r"\'", "", str(i))
>>> s
'[data1][data2][data3]'
How about this?
data = [['data1'], ['data2'], ['data3']]
result = " ".join('[' + a[0] + ']' for a in data)
print(result)
How about this:
In [13]: a = [['data1'],['data2'],['data3']]
In [14]: import json
In [15]: temp = " ".join([json.dumps(x) for x in a]).replace("\"", "")
In [16]: temp
Out[16]: '[data1] [data2] [data3]'
Try the following. This can also be achieved by "Reduce":
from functools import reduce
data = [['data1'], ['data2'], ['data3']]
print(list(reduce(lambda x,y : x+y, data)))
output: ['data1', 'data2', 'data3']
['column1:abc,def', 'column2:hij,klm', 'column3:xyz,pqr']
I want to get the values after the :. Currently if I split it takes into account column1, column2, column3 as well, which I dont want. I want only the values.
This is similar to key-values pair in dictionary. The only dis-similarity is that it is list of strings.
How will I split it?
EDITED
user_widgets = Widgets.objects.filter(user_id = user_id)
if user_widgets:
for widgets in user_widgets:
widgets_list = widgets.gadgets_list //[u'column1:', u'column2:', u'column3:widget_basicLine']
print [item.split(":")[1].split(',') for item in widgets_list] //yields list index out of range
But when the widgets_list value is copied from the terminal and passed it runs correctly.
user_widgets = Widgets.objects.filter(user_id = user_id)
if user_widgets:
for widgets in user_widgets:
widgets_list = [u'column1:', u'column2:', u'column3:widget_basicLine']
print [item.split(":")[1].split(',') for item in widgets_list] //prints correctly.
Where I'm going wrong?
You can split items by ":", then split the item with index 1 by ",":
>>> l = ['column1:abc,def', 'column2:hij,klm', 'column3:xyz,pqr']
>>> [item.split(":")[1].split(',') for item in l]
[['abc', 'def'], ['hij', 'klm'], ['xyz', 'pqr']]
Nothing wrong with a 'for' loop and testing if your RH has actual data:
li=[u'column1:', u'column2:', u'column3:widget_basicLine', u'column4']
out=[]
for us in li:
us1,sep,rest=us.partition(':')
if rest.strip():
out.append(rest)
print out # [u'widget_basicLine']
Which can be reduced to a list comprehension if you wish:
>>> li=[u'column1:', u'column2:', u'column3:widget_basicLine', u'column4']
>>> [e.partition(':')[2] for e in li if e.partition(':')[2].strip()]
[u'widget_basicLine']
And you can further split by the comma if you have data:
>>> li=[u'column1:', u'column2:a,b', u'column3:c,d', u'column4']
>>> [e.partition(':')[2].split(',') for e in li if e.partition(':')[2].strip()]
[[u'a', u'b'], [u'c', u'd']]
I have a (python) list of lists as below
biglist=[ ['1','123-456','hello','there'],['2','987-456','program'],['1','123-456','list','of','lists'] ]
I need to get this in the following format
biglist_modified=[ ['1','123-456','hello there'],['2','987-456','program'],['1','123-456','list of lists'] ]
I need to concatenate the third element onwards in each inner list.I tried to do this by using list comprehensions,
def modify_biglist(bigl):
ret =[]
for alist in bigl:
alist[2] = ' '.join(alist[2:])
del alist[3:]
ret.append(alist)
return ret
This does the job..but it looks a bit convoluted -having a local variable ret and using del? Can someone suggest something better
[[x[0], x[1], " ".join(x[2:])] for x in biglist]
or, in-place:
for x in biglist:
x[2:] = [" ".join(x[2:])]
To modify your list in place, you could use the following simplification of your code:
for a in big_list:
a[2:] = [" ".join(a[2:])]
This ought to do it:
[x[:2] + [" ".join(x[2:])] for x in biglist]
Slightly shorter.