a = [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
print(a)
the output is ['Python Language', 'Python Programming', 'C Language', 'C Programming']
I thought that two list added together should be like ['Python ','C ','Language','Programming']
Simply "deconstruct" the comprehension from left to right, it is the same as nesting for loops to give you the Cartesian product of the two lists:
a = []
for x in ['Python ','C ']:
for y in ['Language','Programming']:
a.append(x+y)
# ['Python Language', 'Python Programming', 'C Language', 'C Programming']
What you had in mind as expected output is the result of a list concatenation like
a = ['Python ','C '] + ['Language','Programming']
# ['Python ', 'C ', 'Language', 'Programming']
Related
Could someone help me with the below? thank you in advance
list1 = ['123', '456', '789']
list2 = ['some text', 'some more text', 'additional string']
for x,y in zip(list1,list2):
listFinal = [x+' ' + y for x in list1 for y in list2]
Currentresult:
['123 some text', '123 some more text', '123 additional string', '456 some text', '456 some more text', '456 additional string', '789 some text', '789 some more text', '789 additional string']
expectedResult:
['123 some text', '456 some more text', '789 additional string']
Using some functional utils:
listFinal = [*map(' '.join, zip(list1, list2))]
Docs on:
map
zip
str.join
listFinal = [x+' ' + y for x in list1 for y in list2]
This makes the zip() function useless. You are iterating over the first list, then through the second list. This makes 3 copies of the element.
You can view it as follows:
for x in list1:
for y in list2:
print(x+" "+y)
This is what the code is currently doing. Your zip() method was right.
You can do this instead.
list1 = ['123', '456', '789']
list2 = ['some text', 'some more text', 'additional string']
list3=[x + ' ' + y for x, y in zip(list1, list2)]
you could just do:
for i in range(0, len(list1) ):
list1[i] += " " + list2[i]
Say I have two Python lists containing strings that may or may not be of the same length.
list1 = ['a','b']
list2 = ['c','d','e']
I want to get the following result:
l = ['a c','a d','a e','b c','b d','b e']
The final list all possible combinations from the two lists with a space in between them.
One method I've tried is with itertools
import itertools
for p in itertools.permutations(, 2):
print(zip(*p))
But unfortunately this was not what I needed, as it did not return any combinations at all.
First make all possible combinations of the two lists, then use list comprehension to achieve the desired result:
list1 = ['a', 'b']
list2 = ['c', 'd', 'e']
com = [(x,y) for x in list1 for y in list2]
print([a + ' ' + b for (a, b) in com]) # ['a c', 'a d', 'a e', 'b c', 'b d', 'b e']
What you want is a cartesian product.
Code:
import itertools
list1 = ['a', 'b']
list2 = ['c', 'd', 'e']
l = ['%s %s' % (e[0], e[1]) for e in itertools.product(list1, list2)]
print(l)
result:
['a c', 'a d', 'a e', 'b c', 'b d', 'b e']
This is another possible method:
list1=['a','b']
list2=['c','d','e']
list3=[]
for i in list1:
for j in list2:
list3.append(i+" "+j)
print(list3)
One-Liner Solution, Use list comprehension and add the items of list
list1 = ['a','b']
list2 = ['c','d','e']
print([i+j for i in list1 for j in list2])
I have two lists that I'm trying to combine, one is a list of cities, and another is a list of states.
Here's what my city list looks like:
print(combined_city_list)
[['Los Angeles', 'Long Beach', 'Anaheim'], ['Dallas', 'Fort Worth'], ['Miami', 'Fort Lauderdale'], ['Minneapolis', 'St Paul'], ['Louisville', 'Jefferson County'], ['North Port', 'Sarasota', 'Bradenton'], ['Winston', 'Salem'], ['Santa Maria', 'Santa Barbara'], ['Crestview', 'Fort Walton Beach', 'Destin'], ['Macon', 'Bibb County'], ['Champaign', 'Urbana'], ['Lafayette', 'West Lafayette'], ['California', 'Lexington Park'], ['Pinehurst', 'Southern Pines'], ['Hermiston', 'Pendleton'], ['Wisconsin Rapids', 'Marshfield'], ['Arkansas City', 'Winfield']]
Here's what my state list looks like:
print(combined_state_list)
[[' CA'], [' TX'], [' FL'], [' MN'], [' KY'], [' FL'], [' NC'], [' CA'], [' FL'], [' GA'], [' IL'], [' IN'], [' MD'], [' NC'], [' OR'], [' WI'], [' KS']]
This is what I've tried:
combined_state_short = [i[0] for i in combined_state_list]
combined_city_state = []
for c, s in zip (combined_city_list, combined_state_list):
for i in c:
combined_city_state = str(i) + ',' + str(s)
print(combined_city_state)
I get this as the output:
Winfield,[' KS']
I want something like this:
['Los Angeles, CA', 'Long Beach, CA' ...]
In your case
newlist = [z + ',' + y[0] for x , y in zip(combined_city_list,combined_state_list) for z in x]
This will work:
[city + ',' + state for (cities, (state, *_)) in zip(combined_city_list, combined_state_list) for city in cities]
Maybe more clear for beginner in that form:
new_list = []
for cities, state in zip(combined_city_list, combined_state_list):
for city in cities:
new_list.append(city + ',' + state[0])
new_list
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an array that contains numbers and characters, e.g. ['A 3', 'C 1', 'B 2'], and I want to sort it using the numbers in each element.
I tried the below code but it did not work
def getKey(item):
item.split(' ')
return item[1]
x = ['A 3', 'C 1', 'B 2']
print sorted(x, key=getKey(x))
To be safe, I'd recommend you to strip everything but the digits.
>>> import re
>>> x = ['A 3', 'C 1', 'B 2', 'E']
>>> print sorted(x, key=lambda n: int(re.sub(r'\D', '', n) or 0))
['E', 'C 1', 'B 2', 'A 3']
With your method;
def getKey(item):
return int(re.sub(r'\D', '', item) or 0)
>>> print sorted(x, key=getKey)
['E', 'C 1', 'B 2', 'A 3']
What you have, plus comments to what's not working :P
def getKey(item):
item.split(' ') #without assigning to anything? This doesn't change item.
#Also, split() splits by whitespace naturally.
return item[1] #returns a string, which will not sort correctly
x = ['A 3', 'C 1', 'B 2']
print sorted(x, key=getKey(x)) #you are assign key to the result of getKey(x), which is nonsensical.
What it should be
print sorted(x, key=lambda i: int(i.split()[1]))
This is one way to do it:
>>> x = ['A 3', 'C 1', 'B 2']
>>> y = [i[::-1] for i in sorted(x)]
>>> y.sort()
>>> y = [i[::-1] for i in y]
>>> y
['C 1', 'B 2', 'A 3']
>>>
I have a list of words (strings), say:
word_lst = ['This','is','a','great','programming','language']
And a second list with sub-strings, say:
subs_lst= ['This is', 'language', 'a great']
And let's suppose each sub-string in subs_lst appears only one time in word_lst. (sub-strings can be of any length)
I want an easy way to find the hierarchical position of the sub-strings in the word_lst.
So what I want is to order subs_lst according to they appearance in word_lst.
In the previous example, the output would be:
out = ['This is', 'a great', language]
Does anyone know an easy way to do this?
There's probably a faster way to do this, but this works, at least:
word_lst = ['This','is','a','great','programming','language']
subs_lst= ['This is', 'language', 'a great']
substr_lst = [' '.join(word_lst[i:j]) for i in range(len(word_lst)) for j in range(i+1, len(word_lst)+1)]
sorted_subs_list = sorted(subs_lst, key=lambda x:substr_lst.index(x))
print sorted_subs_list
Output:
['This is', 'a great', 'language']
The idea is to build a list of every substring in word_lst, ordered so that all the entries that start with "This" come first, followed by all the entries starting with "is", etc.. We store that in substr_lst.
>>> print substr_lst
['This', 'This is', 'This is a', 'This is a great', 'This is a great programming', 'This is a great programming language', 'is', 'is a', 'is a great', 'is a great programming', 'is a great programming language', 'a', 'a great', 'a great programming', 'a great programming language', 'great', 'great programming', 'great programming language', 'programming', 'programming language', 'language']
Once we have that list, we sort subs_list, using the index of each entry in substr_list as the key to sort by:
>>> substr_lst.index("This is")
1
>>> substr_lst.index("language")
20
>>> substr_lst.index("a great")
12
The intermediate step seems unneeded to me. Why not just make the word list a single string and find the substrings in that?
sorted(subs_lst, key = lambda x : ' '.join(word_lst).index(x))