I've array of string in python, I'm iterating over the loop each value and trying to append ('|') symbol using below code. But its not appending as expected
result_list = []
new_value = 'iek,33833,,sdfd,lope'
my_list = ['abc,1234,,ickd,sold', 'yeje,38393,,dkdi,eole', 'euei,38393,,idkd,dikd']
for val in my_list:
result_list.append(val + '|')
res = result_list.append(new_value) + '|')
print res
I'm trying to print the list of string including new string at last. But its giving me below error:
TypeError: can only concatenate list (not "str") to list
Sample output:
abc,1234,,ickd,sold|yeje,38393,,dkdi,eole|euei,38393,,idkd,dikd|iek,33833,,sdfd,lope|
Thanks a lot for your help!
Use a list comprehension to add |, then join():
''.join([x+'|' for x in my_list])
# abc,1234,,ickd,sold|yeje,38393,,dkdi,eole|euei,38393,,idkd,dikd|
Simply using '|'.join() won't get you the final | you require.
This will directly give you the result.
'|'.join(my_list) + '|'
No need to iterate, you can use join() to achieve this.
my_list = ['abc,1234,,ickd,sold', 'yeje,38393,,dkdi,eole', 'euei,38393,,idkd,dikd']
print '|'.join(my_list)
output:
abc,1234,,ickd,sold|yeje,38393,,dkdi,eole|euei,38393,,idkd,dikd
result_list = []
my_list = ['abc,1234,,ickd,sold', 'yeje,38393,,dkdi,eole', 'euei,38393,,idkd,dikd']
for val in my_list:
result_list.append(str(val)+"|")
# result_list.append()
print ''.join(result_list)
Related
I have a list of list elements that I'm modifying. And after that modification I want to put them into a list that have the same structure as the original one:
list_data_type = [
[['void1']], [['uint8']], [['uint8'], ['uint32']], [['void2']], [['void3']], [['void4']], [['void5']]
]
Firstly I check for elements that have more than one element. So in this case that would be element with index number = 2. Then I change it into a string, strip it from brackets [] and " " marks and convert it to a list. Then I take other elements and do the same thing. After conversion I want to create a new list with those elements, but without unnecessary symbols. So my desired output would look like this:
list_data_converted = [
['void1'], ['uint8'], ['uint8', 'uint32'], ['void2'], ['void3'], ['void4'], ['void5']
]
Conversion works and I can print out elements, but I have a problem with appending them to a list. My code saves only last value from original list:
def Convert(string):
li = list(string.split(" "))
return li
for element in list_data_type:
if type(element) == list:
print("element is a:", element, type(element))
if len(element) > 1:
id_of_el = list_data_type.index(element)
el_str = str(element).replace('[', '').replace("'", '').replace("'", '').replace(']', '').replace(',', '')
el_con = Convert(el_str)
elif len(element <= 1):
elements_w_1_el = element
list_el = []
for i in range(len(elements_w_1_el)):
el_str_2 = str(element).replace('[', '').replace("'", '').replace("'", '').replace(']', '').replace(',', '')
list_el.append(elements_w_1_el[i])
And my out instead looking like "list_data_converted", has only one element - ['void5']. How do I fix that?
Converting a list to a string to flatten it is a very... cumbersome approach.
Try simple list-comprehension:
list_data_type = [[v[0] for v in l] for l in list_data_type]
Type casting the list into a string and then replacing the characters and then again converting the string into list might be bad way to achieve what you're doing.
Try this :
def flatten(lst):
if lst == []:
return lst
if isinstance(lst[0], list):
return flatten(lst[0]) + flatten(lst[1:])
return lst[:1] + flatten(lst[1:])
list_data_converted = [flatten(element) for element in list_data_type]
This actually flattens any list item inside list_data_type and keep them in a single list. This should work with any depth of list inside list.
Output print(list_data_converted) would give the following :
[
['void1'], ['uint8'], ['uint8', 'uint32'], ['void2'], ['void3'], ['void4'], ['void5']
]
I need to get:
'W1NaCl U1NaCl V1NaCl'
from:
[['W1NaCl'], ['U1NaCl'], ['V1NaCl']]
How to get required output in pythonic way
items = [['W1NaCl'], ['U1NaCl'], ['V1NaCl']]
res = " ".join([item[0] for item in items])
Which yields: W1NaCl U1NaCl V1NaCl
You can do:
[[i] for i in 'W1NaCl U1NaCl V1NaCl'.split()]
Split will chop it into words, and the list comprehension will make the inner-arrays
I'm trying to create a big list that will contain lists of strings. I iterate over the input list of strings and create a temporary list.
Input:
['Mike','Angela','Bill','\n','Robert','Pam','\n',...]
My desired output:
[['Mike','Angela','Bill'],['Robert','Pam']...]
What i get:
[['Mike','Angela','Bill'],['Angela','Bill'],['Bill']...]
Code:
for i in range(0,len(temp)):
temporary = []
while(temp[i] != '\n' and i<len(temp)-1):
temporary.append(temp[i])
i+=1
bigList.append(temporary)
Use itertools.groupby
from itertools import groupby
names = ['Mike','Angela','Bill','\n','Robert','Pam']
[list(g) for k,g in groupby(names, lambda x:x=='\n') if not k]
#[['Mike', 'Angela', 'Bill'], ['Robert', 'Pam']]
Fixing your code, I'd recommend iterating over each element directly, appending to a nested list -
r = [[]]
for i in temp:
if i.strip():
r[-1].append(i)
else:
r.append([])
Note that if temp ends with a newline, r will have a trailing empty [] list. You can get rid of that though:
if not r[-1]:
del r[-1]
Another option would be using itertools.groupby, which the other answerer has already mentioned. Although, your method is more performant.
Your for loop was scanning over the temp array just fine, but the while loop on the inside was advancing that index. And then your while loop would reduce the index. This caused the repitition.
temp = ['mike','angela','bill','\n','robert','pam','\n','liz','anya','\n']
# !make sure to include this '\n' at the end of temp!
bigList = []
temporary = []
for i in range(0,len(temp)):
if(temp[i] != '\n'):
temporary.append(temp[i])
print(temporary)
else:
print(temporary)
bigList.append(temporary)
temporary = []
You could try:
a_list = ['Mike','Angela','Bill','\n','Robert','Pam','\n']
result = []
start = 0
end = 0
for indx, name in enumerate(a_list):
if name == '\n':
end = indx
sublist = a_list[start:end]
if sublist:
result.append(sublist)
start = indx + 1
>>> result
[['Mike', 'Angela', 'Bill'], ['Robert', 'Pam']]
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']
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.