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.
Related
I am working on the lists but I had a problem.
There is a list as follows:
First_last_Name = [['hassan','abasi'],['mohammad','sajadi'],['bahman','mardomani'],['sarah','masti']]
Now we want to convert it as follows:
First_last_Name = ['hassan abasi','mohammad sajadi','bahman mardomani','sarah masti']
I want to try to write it in one line with lambda.
The code I am trying to apply in one line is as follows:
full_str = [(lambda x: str(x))(x) for x in First_last_Name]
output :
["['hassan', 'abasi']",
"['mohammad', 'sajadi']",
"['bahman', 'mardomani']",
"['sarah', 'masti']"]
But I can't delete that internal list and turn it into a string.
You can do it with a list comprehension and join
result = [" ".join(i) for i in First_last_Name]
Result:
['hassan abasi', 'mohammad sajadi', 'bahman mardomani', 'sarah masti']
First_last_Name = [['hassan','abasi'],['mohammad','Sajadi'],['bahman','mardomani'],['sarah','masti']]
new_list = [ " ".join(i) for i in First_last_Name]
I'd prefer #sembei-norimaki 's solution. But as you asked about lambda:
result = list(map(lambda x: ' '.join(x), First_last_Name))
or even simpler:
result = list(map(' '.join, First_last_Name))
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
This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 2 years ago.
A simple list, that I want to loop through to print each element twice. Each time to add a different prefix. The output will be appended into a new list.
List1 = ["9016","6416","9613"]
The ideal result is:
['AB9016', 'CD9016', 'AB6416', 'CD6416', AB9613', 'CD9613']
I have tried below and but the output is:
new_list = []
for x in List1:
for _ in [0,1]:
new_list.append("AB" + x)
new_list.append("CD" + x)
print (new_list)
['AB9016', 'CD9016', 'AB9016', 'CD9016', 'AB6416', 'CD6416', 'AB6416', 'CD6416', 'AB9613', 'CD9613', 'AB9613', 'CD9613']
And I can't use:
new_list.append("AB" + x).append("CD" + x)
What's the proper way to do it? Thank you.
The problem is caused by the inner loop: the two appends will be called twice. Fixed code:
new_list = []
for x in List1:
new_list.append("AB" + x)
new_list.append("CD" + x)
Regarding chaining append calls: It would work if append returned the list (with the new item appended to it), but this is not the case, the append method returns None (doc).
Also could try an easy comprehension:
List1 = ["9016","6416","9613"]
result = [j+i for i in List1 for j in ('AB','CD')]
# ['AB9016', 'CD9016', 'AB6416', 'CD6416', 'AB9613', 'CD9613']
The fastest method is to use the list comprehension. We are using 2 list comprehension to create the desired_list. Note that I also used the f string so I could easily ad the 'ABandCD` prefix.
list1 = ["9016","6416","9613"]
desired_list = [f'AB{x}' for x in list1] + [f'CD{x}' for x in list1]
print(desired_list)
I would use itertools.product for that task following way
import itertools
list1 = ["9016","6416","9613"]
prefixes = ["AB","CD"]
result = [x+y for y,x in itertools.product(list1,prefixes)]
print(result)
Output:
['AB9016', 'CD9016', 'AB6416', 'CD6416', 'AB9613', 'CD9613']
Here is a solution using itertools.product:
from itertools import product
lst1 = ['9016', '6416', '9613']
lst2 = ['AB', 'CD']
result = list(map(''.join, map(reversed, product(lst1, lst2))))
we can use sum too:
In [25]: sum([[f'AB{i}',f'CD{i}'] for i in List1],[])
Out[25]: ['AB9016', 'CD9016', 'AB6416', 'CD6416', 'AB9613', 'CD9613']
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)
I have a list like below - from this i have filter the tables that begin with 'test:SF.AcuraUsage_' (string matching)
test:SF.AcuraUsage_20150311
test:SF.AcuraUsage_20150312
test:SF.AcuraUsage_20150313
test:SF.AcuraUsage_20150314
test:SF.AcuraUsage_20150315
test:SF.AcuraUsage_20150316
test:SF.AcuraUsage_20150317
test:SF.ClientUsage_20150318
test:SF.ClientUsage_20150319
test:SF.ClientUsage_20150320
test:SF.ClientUsage_20150321
I am using this for loop but not sure why it does not work:
for x in list:
if(x 'test:SF.AcuraUsage_'):
print x
I tried this out:
for x in list:
alllist = x
vehiclelist = [x for x in alllist if x.startswith('geotab-bigdata-test:StoreForward.VehicleInfo')]
Still i get the error ' dictionary object has no attribute startswith'.
You shouldn't name your list list, since it overrides the built-in type list
But, if you'd like to filter that list using Python, consider using this list comprehension:
acura = [x for x in list if x.startswith('test:SF.AcuraUsage')]
then, if you'd like to output it
for x in acura:
print(x)
List comprehensions are good for that.
Get a list with all the items that begin with 'test:SF.AcuraUsage_' :
new_list = [x for x in list if x.startswith('test:SF.AcuraUsage_' ')]
Or the items that do not begin with 'test:SF.AcuraUsage_' :
new_list = [x for x in list if not x.startswith('test:SF.AcuraUsage_' )]
using re module:
import re
for x in list:
ret = re.match('test:SF.AcuraUsage_(.*)',x)
if ret:
print(re.group())