Merging item in two lists with a separator - python-3.5

I have two separate lists, "a" and "b". I'm trying to merge them together so it shows the items in the two lists with a hyphen in between.
I tried to using the zip and join functions but I wasn't able to solve the issue.
a = ['USA', 'Australia', 'Netherlands', 'Sweden', 'France', 'Spain']
b = ['Washington', 'Canberra', 'Amsterdam', 'Stockholm', 'Paris', 'Barcelona']
##I tried using zip
c = CT = zip(a,b)
##I got:
[('USA', 'Washington'),
('Australia', 'Canberra'),
('Netherlands', 'Amsterdam'),
('Sweden', 'Stockholm'),
('France', 'Paris'),
('Spain', 'Barcelona')]
Tried to use join as well, but that didn't work
Ideally, the output should be:
USA-Washington
Australia-Canberra
Netherlands-Amesterdam
Sweden-Stockholm
France-Paris
Spain-Barcelona
Any help would be appreciated.

You can apply a list comprehension over the zipped items:
[x + '-' + y for x,y in zip(a,b)]

You can apply join to each result of zip.
c = ['-'.join(x) for x in zip(a, b)]
Or you can use a for loop.
c = []
for i in range(min(len(a), len(b))):
c.append('{}-{}'.format(a[i], b[i]))

Related

Elements within a list of lists

I have a below mentioned list:
a= ['1234,5678\n','90123,45678\n']
The expected output I'm working towards is this:
op = [['1234','5678'],['90123','45678']]
Basically a list of lists with individual elements referring to a particular column.
Using the below mentioned code i get the following output:
a = ['1234,5678\n','90123,45678\n']
new_list = []
for element in a:
#remove new lines
new_list.append(element.splitlines())
print(new_list)
output:[['1234,5678'], ['90123,45678']]
Any direction regarding this would be much appreciated.
Check this:
a= ['1234,5678\n','90123,45678\n']
a = ['1234,5678\n','90123,45678\n']
new_list = []
for element in a:
#remove new lines
new_list.append(element.strip("\n").split(","))
print(new_list)
Try this:
a = [i.strip("\n").split(",") for i in a]
Since the strings in your input list appears to follow the CSV format, you can use csv.reader to parse them:
import csv
list(csv.reader(a))
This returns:
[['1234', '5678'], ['90123', '45678']]

Delete sub-list from list in python

I need to remove the sub lists from a list in Python.
For example: The main list A contains
A=[ 'a,b,c', 'd,e,f' , 'g,h,i' , 'g,l,m' , 's,l,k' , 'd,k,l', 'a,g,d' ]
I need to remove the sub lists from A which begin with the items in the following list:
B = ['g','d']
so that Final List A = [ 'a,b,c', 's,l,k' , 'a,g,d' ]
Thanks in advance
Using list comprehension:
print([x for x in A if x[0] not in ['g', 'd']])
You can do it using list comprehension and split(",").
print([e for e in A if e.split(",")[0] not in B])
Output
['a,b,c', 's,l,k', 'a,g,d']
Your output above for your approach is wrong.
2nd Element 'd,e,f' should also be removed as start element 'd' is in second list.

How do you split a string inside a list?

I got this type of strings inside a list :
[['AAAA-BBBBBBB-10.00.00.0', 'AAAAAAAA', '00:00:00:00:00:00', '000', 'BBBBBBB', 'AAAAA:00'], [
when i export this list to csv the strings inside the commas (,) are in different cells but 'AAAA-BBBBBBB-10.00.00.0' is all in one cell. I wanted it to look like this:
[['AAAA-BBBBBBB','10.00.00.0', 'AAAAAAAA', '00:00:00:00:00:00', '000', 'BBBBBBB', 'AAAAA:00'], [
so when i export it to csv file the strings 'AAAA-BBBBBBB','10.00.00.0' will be in 2 different cells.
I tried:
dp1 = [d.replace("-1"," 1").split() for d in data]
but it doesnt work it seems its ignoring it!
You can enumerate the elements of the outer list, change the composition of the 1st item of the inner list and assing it back to your outer list:
data = [['AAAA-BBBBBBB-10.00.00.0', 'AAAAAAAA', '00:00:00:00:00:00',
'000', 'BBBBBBB', 'AAAAA:00'],
[]]
for idx, d in enumerate(data):
if d:
orig = d[0].replace("-1"," 1").split() # create a 2 part list
d = orig + d[1:] # use list slicing
data[idx] = d # assign it back to your big list
print(data)
Output:
[['AAAA-BBBBBBB', '10.00.00.0', 'AAAAAAAA', '00:00:00:00:00:00',
'000', 'BBBBBBB', 'AAAAA:00'],
[]]

Making a dictionary of from a list and a dictionary

I am trying to create a dictionary of codes that I can use for queries and selections. Let's say I have a dictionary of state names and corresponding FIPS codes:
statedict ={'Alabama': '01', 'Alaska':'02', 'Arizona': '04',... 'Wyoming': '56'}
And then I have a list of FIPS codes that I have pulled in from a Map Server request:
fipslist = ['02121', '01034', '56139', '04187', '02003', '04023', '02118']
I want to sort of combine the key from the dictionary (based on the first 2 characters of the value of that key) with the list items (also, based on the first 2 characters of the value of that key. Ex. all codes beginning with 01 = 'Alabama', etc...). My end goal is something like this:
fipsdict ={'Alabama': ['01034'], 'Alaska':['02121', '02003','02118'], 'Arizona': ['04187', '04023'],... 'Wyoming': ['56139']}
I would try to set it up similar to this, but it's not working quite correctly. Any suggestions?
fipsdict = {}
tempList = []
for items in fipslist:
for k, v in statedict:
if item[:2] == v in statedict:
fipsdict[k] = statedict[v]
fipsdict[v] = tempList.extend(item)
A one liner with nested comprehensions:
>>> {k:[n for n in fipslist if n[:2]==v] for k,v in statedict.items()}
{'Alabama': ['01034'],
'Alaska': ['02121', '02003', '02118'],
'Arizona': ['04187', '04023'],
'Wyoming': ['56139']}
You will have to create a new list to hold matching fips codes for each state. Below is the code that should work for your case.
for state,two_digit_fips in statedict.items():
matching_fips = []
for fips in fipslist:
if fips[:2] == two_digit_fips:
matching_fips.append(fips)
state_to_matching_fips_map[state] = matching_fips
>>> print(state_to_matching_fips_map)
{'Alabama': ['01034'], 'Arizona': ['04187', '04023'], 'Alaska': ['02121', '02003', '02118'], 'Wyoming': ['56139']}
For both proposed solutions I need a reversed state dictionary (I assume that each state has exactly one 2-digit code):
reverse_state_dict = {v: k for k,v in statedict.items()}
An approach based on defaultdict:
from collections import defaultdict
fipsdict = defaultdict(list)
for f in fipslist:
fipsdict[reverse_state_dict[f[:2]]].append(f)
An approach based on groupby and dictionary comprehension:
from itertools import groupby
{reverse_state_dict[k]: list(v) for k,v
in (groupby(sorted(fipslist), key=lambda x:x[:2]))}

looping over function with multiple argument

Beginning python user here. This seems like a simple question but I haven't been able to find an answer or at least recognize an answer.
I have a function as follows:
def standardize(columns, dictionary):
for x in columns:
df.iloc[:,x] = df.iloc[:,x].map(dictionary)
The function takes a list of columns and recodes all the values in that column according to the associated dictionary.
Rather than calling the function a dozen times for each list of columns and its associated dictionary:
standardize([15,19,27], dict1)
standardize([47,65,108], dict2)
standardize([49,53,55,90], dict3)
ideally I'd like it to loop over. a list of all the column lists and a list of all the dictionaries. something like:
for column_list in [[list1], [list2], [list3]]:
standardize(column_list, associated_dictionary)
How would I go about this?
No, there's no need to loop when considering single replacement. You can use applymap instead:
col_list = [...]
df.iloc[:, columns] = df.iloc[:, columns].applymap(dictionary.get)
Now, for multiple sets, you can zip your column lists and dictionaries and iterate:
column_lists = [col_list1, col_list2, ...]
dictionaries = [dict1, dict2, ...]
for c, d in zip(column_lists, dictionaries):
df.iloc[:, c] = df.iloc[:, c].applymap(d.get)

Resources