How to pin two lines?

I have two lists:

country_name = ['South Africa', 'India', 'United States'] country_code = ['ZA', 'IN', 'US'] 

I want to group the name of the country and its corresponding code together, and then do a sort operation to do some processing

When I tried to pin these 2 lists, I get the 1st character from both lists as output.

I also tried to do this:

 for i in xrange(0,len(country_code): zipped = zip(country_name[i][:],country_code[i][:]) ccode.append(zipped) 

to freeze the entire line, but it did not work. Also, I'm not sure that after zipping up list 2, I can sort the resulting list or not.

+4
source share
2 answers

the answer is in your question - use zip :

 >>> country_name = ['South Africa', 'India', 'United States'] >>> country_code = ['ZA', 'IN', 'US'] >>> zip(country_name, country_code) [('South Africa', 'ZA'), ('India', 'IN'), ('United States', 'US')] 

If you have lists with different lengths, you can use itertools.izip_longest :

 >>> from itertools import izip_longest >>> country_name = ['South Africa', 'India', 'United States', 'Netherlands'] >>> country_code = ['ZA', 'IN', 'US'] >>> list(izip_longest(country_name, country_code)) [('South Africa', 'ZA'), ('India', 'IN'), ('United States', 'US'), ('Netherlands', None)] 
+4
source

You are using zip() incorrectly; use it with two lists:

 zipped = zip(country_name, country_code) 

You apply it for each country name and country code separately:

 >>> zip('South Africa', 'ZA') [('S', 'Z'), ('o', 'A')] 

zip() combines two input sequences by combining each element; in lines, individual characters are elements of a sequence. Since there are only two characters in country codes, you get lists of two items, each of which consists of paired pairs.

Once you combine both lists into a new one, you can certainly sort this list either on the first or on the second element:

 >>> zip(country_name, country_code) [('South Africa', 'ZA'), ('India', 'IN'), ('United States', 'US')] >>> sorted(zip(country_name, country_code)) [('India', 'IN'), ('South Africa', 'ZA'), ('United States', 'US')] >>> from operator import itemgetter >>> sorted(zip(country_name, country_code), key=itemgetter(1)) [('India', 'IN'), ('United States', 'US'), ('South Africa', 'ZA')] 
+7
source

Source: https://habr.com/ru/post/1494211/


All Articles