list1 = ["palani", "samy","be"]
list2 = ["palani", "samys","be"]
def find_common(list1,list2):
for x in list1:
for y in list2:
if x == y :
list2.remove(x)
print" unique string 1:",list1
print" unique string 2:",list2
print" combained string 2:",list1.append(list2)
find_common(list1,list2)
Why am I getting None?
This could be accomplished by using set:
a = ['hello', 'world']
b = ['hello', 'universe']
unique = list(set(a + b))
print(unique)
# ['universe', 'hello', 'world']
Note: this won't work for a list of dictionaries!
import numpy as np
np.unique(list1+list2) # keeps only non dublicates
this is also keeps the order incase that was a priority
The list.append method modifies the list in-place and returns None. You should use the + operator to merge the two lists instead.
Change:
print" combained string 2:",list1.append(list2)
to:
print" combained string 2:",list1+list2
list3 = list1[:]
[list3.append(i) for i in list2 if i not in list1]
print(l3)
['palani', 'samy', 'be', 'samys']
you may try:
def find_common(list1,list2):
return list(set(list1+list2))
You can use set operations to achieve this.
unique = list(set(list1).symmetric_difference(set(list2)))
Related
I have two lists of tuples, say,
list1 = [('item1',),('item2',),('item3',), ('item4',)] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple
Expected output: 'item4' # Item that doesn't exist in list2
As shown in above example I want to check which item in tuples in list 1 does not exist in first index of tuples in list 2. What is the easiest way to do this without running two for loops?
Assuming your tuple structure is exactly as shown above, this would work:
tuple(set(x[0] for x in list1) - set(x[0] for x in list2))
or per #don't talk just code, better as set comprehensions:
tuple({x[0] for x in list1} - {x[0] for x in list2})
result:
('item4',)
This gives you {'item4'}:
next(zip(*list1)) - dict(list2).keys()
The next(zip(*list1)) gives you the tuple ('item1', 'item2', 'item3', 'item4').
The dict(list2).keys() gives you dict_keys(['item1', 'item2', 'item3']), which happily offers you set operations like that set difference.
Try it online!
This is the only way I can think of doing it, not sure if it helps though. I removed the commas in the items in list1 because I don't see why they are there and it affects the code.
list1 = [('item1'),('item2'),('item3'), ('item4')] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple
not_in_tuple = []
OutputTuple = [(a) for a, b in list2]
for i in list1:
if i in OutputTuple:
pass
else:
not_in_tuple.append(i)
for i in not_in_tuple:
print(i)
You don't really have a choice but to loop over the two lists. Once efficient way could be to first construct a set of the first elements of list2:
items = {e[0] for e in list2}
list3 = list(filter(lambda x:x[0] not in items, list1))
Output:
>>> list3
[('item4',)]
Try set.difference:
>>> set(next(zip(*list1))).difference(dict(list2))
{'item4'}
>>>
Or even better:
>>> set(list1) ^ {x[:1] for x in list2}
{('item4',)}
>>>
that is a difference operation for sets:
set1 = set(j[0] for j in list1)
set2 = set(j[0] for j in list2)
result = set1.difference(set2)
output:
{'item4'}
for i in list1:
a=i[0]
for j in list2:
b=j[0]
if a==b:
break
else:
print(a)
Let's say I have this list:
list = ['hello','world','spam','eggs']
and I want to clear everything from that list EXCEPT 'world'.
How do I do this?
You can use list comprehension for this as:
l = ['hello','world','spam','eggs']
only = [item for item in l if item == 'world'] # ['world']
if you want to do it for multiple words you can store you filters as this:
l = ['hello','world','spam','eggs']
filters = ['hello', 'world']
only = [item for item in l if item in filters] # ['hello', 'world']
or you can also use the filter function as this:
l = ['hello','world','spam','eggs']
only = filter(lambda x: x == 'hello', l) # ['hello']
In totaly, consider now to call your varibles by the type name, calling something list override the list constructor, which can lead for other prolbems in the future
another solution is to check if 'world' exists in your list. If not assign an empty list.
list = ['hello','world','spam','eggs']
if 'world' in list:
list = ['world'] * list.count('world')
else:
list = []
print(list)
I have a simple list that I am splitting and concatenating. My code uses for loop and if condition and ugly. Can you suggest a better way using list comprehension?
My code
mylist = ['10.10.10.1','10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5','10.10.10.6']
mylist = [i.split(",") for i in mylist]
list =[]
for x,y in enumerate(mylist):
if len(y) == 1:
list.append(y[0])
else:
for z in y:
list.append(z)
print(list)
I am getting the below result and exactly the way i want
['10.10.10.1','10.10.10.2','10.10.10.3','10.10.10.4','10.10.10.5','10.10.10.6']
You want:
[s for string in mylist for s in string.split(',')]
Note, your original approach wouldn't be so bad if you just simplified. No need for enumerate and no need to check the length, so just:
final_list =[]
for sub in mylist:
for s in sub:
final_list.append(s)
By the way, you shouldn't shadow the built-in list. Use another name
I agree with #juanpa.arrivillaga. However hope we can avoid that second looping since he is checking for empty values returning while splitting
In [7]: s=['10.10.10.1','','10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5','10.10.10.6']
In [8]: [splitRec for rec in s for splitRec in rec.split(',') if splitRec]
Out[8]:
['10.10.10.1',
'10.10.10.2',
'10.10.10.3',
'10.10.10.4',
'10.10.10.5',
'10.10.10.6']
In [9]: s=['10.10.10.1',',,','10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5','10.10.10.6']
In [10]: [splitRec for rec in s for splitRec in rec.split(',') if splitRec]Out[10]:
['10.10.10.1',
'10.10.10.2',
'10.10.10.3',
'10.10.10.4',
'10.10.10.5',
'10.10.10.6']
Not a comprehension, but good anyway, I think.
','.join(mylist).split(',')
You can first just split each string on ',':
>>> mylist = ['10.10.10.1','10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5','10.10.10.6']
>>> split_str = [x.split(',') for x in mylist]
>>> split_str
[['10.10.10.1'], ['10.10.10.2', '10.10.10.3', '10.10.10.4', '10.10.10.5'], ['10.10.10.6']]
Then if you want to flatten it, you can use itertools.chain.from_iterable:
>>> from itertools import chain
>>> list(chain.from_iterable(split_str))
['10.10.10.1', '10.10.10.2', '10.10.10.3', '10.10.10.4', '10.10.10.5', '10.10.10.6']
I have a python list
list1 = ['TC_TEST1', 'TC_TEST1_TEST2', 'TC_TEST3', 'TC_TEST1TEST2']
sublist1 = ['TEST1', 'TEST3']
Desired output is
result = ['TC_TEST1', 'TC_TEST3']
It should not contain patterns in sublist1 that occur in middle or other places in the string.
I tried using
result = [s for s in list1 if any(xs in s for xs in sublist1)]
but this also prints the patterns wherever it occurs in the string, not only the ending part.
You can try this:
list1 = {'TC_TEST1', 'TC_TEST1_TEST2', 'TC_TEST3', 'TC_TEST1TEST2'}
sublist1 = { 'TEST1', 'TEST3'}
final_list = [i for i in list1 if any(i.endswith(b) for b in sublist1)]
Output:
set(['TC_TEST3', 'TC_TEST1'])
Advanced feature with tuples:
sublist1 = ('TEST1', 'TEST3')
final_list = [i for i in list1 if i.endswith(sublist1)]
First, you need to notice that you haven't defined python lists, but sets. These are the equivalent lists derived from your defined sets (notice the []notation):
list1 = ['TC_TEST1TEST2', 'TC_TEST3', 'TC_TEST1', 'TC_TEST1_TEST2']
sublist1 = ['TEST1', 'TEST3']
If you need to filter the strings that only ends with a list of possible substrings, you can call the endswith method of a Python string passing a tuple of strings as an argument. That way, your desired output can be derived using the following expression:
result = [s for s in list1 if s.endswith(tuple(sublist1))]
Actual output is:
>>> result
['TC_TEST3', 'TC_TEST1']
Instead of using in use endswith() function so just replace result = [s for s in list1 if any(xs in s for xs in sublist1)]
with result = [s for s in list1 if any(s.endswith(xs) for xs in sublist1)],.
I have two lists where I am trying to see if there is any matches between substrings in elements in both lists.
["Po2311tato","Pin2231eap","Orange2231edg","add22131dfes"]
["2311","233412","2231"]
If any substrings in an element matches the second list such as "Po2311tato" will match with "2311". Then I would want to put "Po2311tato" in a new list in which all elements of the first that match would be placed in the new list. So the new list would be ["Po2311tato","Pin2231eap","Orange2231edg"]
You can use the syntax 'substring' in string to do this:
a = ["Po2311tato","Pin2231eap","Orange2231edg","add22131dfes"]
b = ["2311","233412","2231"]
def has_substring(word):
for substring in b:
if substring in word:
return True
return False
print filter(has_substring, a)
Hope this helps!
This can be a little more concise than the jobby's answer by using a list comprehension:
>>> list1 = ["Po2311tato","Pin2231eap","Orange2231edg","add22131dfes"]
>>> list2 = ["2311","233412","2231"]
>>> list3 = [string for string in list1 if any(substring in string for substring in list2)]
>>> list3
['Po2311tato', 'Pin2231eap', 'Orange2231edg']
Whether or not this is clearer / more elegant than jobby's version is a matter of taste!
import re
list1 = ["Po2311tato","Pin2231eap","Orange2231edg","add22131dfes"]
list2 = ["2311","233412","2231"]
matchlist = []
for str1 in list1:
for str2 in list2:
if (re.search(str2, str1)):
matchlist.append(str1)
break
print matchlist