Comparing entries in a list to another list - python

Using Python 3.9.5
a=['Apple', 'Orange', 'peaches']
b=[['Lettuce', 'Apple', 'eggs'],['potato', 'tomato', 'pepper']]
I want to compare for any values in a to b and if there is a match continue to the next list (
my program generates lists of key words) i want to compare the initial list "a" to the lists i have and if there is a match go next and if there is no match then do something like print that list.
this is what i tried, not working though
for i in b:
if any(x in a for x in [b, c]):
continue
else:
print(#the current sublist)
i would like to say that with integers this code works but with lists or strings it doesn't, appreciate the feedback

a = ['Apple', 'Orange', 'peaches']
b = [['Lettuce', 'Apple', 'eggs'], ['potato', 'tomato', 'pepper']]
for el in b:
if any([x in a for x in el]):
print("ok")
else:
print(el)
Returns:
True
False
Explanation:
First of all we iterate over b, so we have el = ['Lettuce', 'Apple', 'eggs'] on the first iteration.
Next we create list of bools: [x in a for x in el]. We check are there elements of a in our current element el: [False, True, False] - for first element of b.
Next we reduce our list of bools ([False, True, False]) to one bool using any()

That should work if I understand the problem correctly:
to_check = ['Apple','Orange','peaches']
list_of_lists = [['Lettuce', 'Apple','eggs'],['potato','tomato','pepper']]
for _list in list_of_lists:
if any([element_to_check in _list for element_to_check in to_check]):
print('Matched')
else:
print('Not matched')

I don't know where are you are getting the variable c. Just replace this line and it will work.
From:
if any(x in a for x in [b,c]):
To:
if any(x in a for x in i):
The value of i is each sub-list in b such as ['Lettuce', 'Apple', 'eggs'] thus your algorithm iterates each item in the sub-list and checks for any element that is also in a.
Here is an improvement to your algorithm. Currently, your algorithm runs at a time complexity of O(z * y * x) where:
x = length of a
y = length of b
z = average length of each sub-list in b
Instead of always traversing the list a, make it a hash table e.g. set, this will make the searches improve from linear O(x) to constant O(1).
a_set = set(a)
for i in b:
if any(x in a_set for x in i):
# Do something or just continue
continue
else:
print(i)
This will improve the time complexity to O(z * y). As a comparison, if we have 20 elements in a, 10 in b, and an average of 3 in each sub-list of b, the previous algorithm using a list a would run 3 * 10 * 20 for a total of 600 iterations, compare to a set a which would only run 3 * 10 for a total of 30 iterations.

Related

How do I use an if... else conditional in the inner loop of a nested list comprehension in Python? [duplicate]

I have a list xs containing a mixture of strings and None values. How can I use a list comprehension to call a function on each string, but convert the None values to '' (rather than passing them to the function)?
I tried:
[f(x) for x in xs if x is not None else '']
but it gives a SyntaxError. What is the correct syntax?
See List comprehension with condition if you are trying to make a list comprehension that omits values based on a condition.
If you need to consider more than two conditional outcomes, beware that Python's conditional expressions do not support elif. Instead, it is necessary to nest if/else conditionals. See `elif` in list comprehension conditionals for details.
You can totally do that. It's just an ordering issue:
[f(x) if x is not None else '' for x in xs]
In general,
[f(x) if condition else g(x) for x in sequence]
And, for list comprehensions with if conditions only,
[f(x) for x in sequence if condition]
Note that this actually uses a different language construct, a conditional expression, which itself is not part of the comprehension syntax, while the if after the for…in is part of list comprehensions and used to filter elements from the source iterable.
Conditional expressions can be used in all kinds of situations where you want to choose between two expression values based on some condition. This does the same as the ternary operator ?: that exists in other languages. For example:
value = 123
print(value, 'is', 'even' if value % 2 == 0 else 'odd')
Let's use this question to review some concepts. I think it's good to first see the fundamentals so you can extrapolate to different cases.
Other answers provide the specific answer to your question. I'll first give some general context and then I'll answer the question.
Fundamentals
if/else statements in list comprehensions involve two things:
List comprehensions
Conditional expressions (Ternary operators)
1. List comprehensions
They provide a concise way to create lists.
Its structure consists of: "brackets containing an expression followed by a for clause, then zero or more for or if clauses".
Case 1
Here we have no condition. Each item from the iterable is added to new_list.
new_list = [expression for item in iterable]
new_list = [x for x in range(1, 10)]
> [1, 2, 3, 4, 5, 6, 7, 8, 9]
Case 2
Here we have one condition.
Example 1
Condition: only even numbers will be added to new_list.
new_list = [expression for item in iterable if condition == True]
new_list = [x for x in range(1, 10) if x % 2 == 0]
> [2, 4, 6, 8]
Example 2
Condition: only even numbers that are multiple of 3 will be added to new_list.
new_list = [expression for item in iterable if condition == True]
new_list = [x for x in range(1, 10) if x % 2 == 0 if x % 3 == 0]
> [6]
But howcome we have one condition if we use two if in new_list?
The prior expression could be written as:
new_list = [x for x in range(1, 10) if x % 2 and x % 3 == 0]
> [6]
We only use one if statement.
This is like doing:
new_list = []
for x in range(1, 10):
if x % 2 == 0 and x % 3 == 0:
new_list.append(x)
> [6]
Example 3
Just for the sake of argument, you can also use or.
Condition: even numbers or numbers multiple of 3 will be added to new_list.
new_list = [x for x in range(1, 10) if x % 2 == 0 or x % 3 == 0]
> [2, 3, 4, 6, 8, 9]
Case 3
More than one condition:
Here we need the help of conditional expressions (Ternary operators).
2.Conditional Expressions
What are conditional expressions? What the name says: a Python expression that has some condition.
<Exp1> if condition else <Exp2>
First the condition is evaluated. If condition is True, then <Exp1> is evaluated and returned. If condition is False, then <Exp2> is evaluated and returned.
A conditional expression with more than one condition:
<Exp1> if condition else <Exp2> if condition else <Exp3>...
An example from Real Python:
age = 12
s = 'minor' if age < 21 else 'adult'
> minor
The value of s is conditioned to age value.
3.List Comprehensions with Conditionals
We put list comprehensions and conditionals together like this.
new_list = [<Conditional Expression> for <item> in <iterable>]
new_list = [<Exp1> if condition else <Exp2> if condition else <Exp3> for <item> in <iterable>]
Condition: even numbers will be added as 'even', the number three will be added as 'number three' and the rest will be added as 'odd'.
new_list = ['even' if x % 2 == 0 else 'number three' if x == 3 else 'odd'
for x in range(1, 10)]
> ['odd', 'even', 'number three', 'even', 'odd', 'even', 'odd', 'even', 'odd']
The answer to the question
[f(x) for x in xs if x is not None else '']
Here we have a problem with the structure of the list: for x in xs should be at the end of the expression.
Correct way:
[f(x) if x is not None else '' for x in xs]
Further reading:
Does Python have a ternary conditional operator?
The specific problem has already been solved in previous answers, so I will address the general idea of using conditionals inside list comprehensions.
Here is an example that shows how conditionals can be written inside a list comprehension:
X = [1.5, 2.3, 4.4, 5.4, 'n', 1.5, 5.1, 'a'] # Original list
# Extract non-strings from X to new list
X_non_str = [el for el in X if not isinstance(el, str)] # When using only 'if', put 'for' in the beginning
# Change all strings in X to 'b', preserve everything else as is
X_str_changed = ['b' if isinstance(el, str) else el for el in X] # When using 'if' and 'else', put 'for' in the end
Note that in the first list comprehension for X_non_str, the order is:
expression for item in iterable if condition
and in the last list comprehension for X_str_changed, the order is:
expression1 if condition else expression2 for item in iterable
I always find it hard to remember that expression1 has to be before if and expression2 has to be after else. My head wants both to be either before or after.
I guess it is designed like that because it resembles normal language, e.g. "I want to stay inside if it rains, else I want to go outside"
In plain English the two types of list comprehensions mentioned above could be stated as:
With only if:
extract_apple for apple in apple_box if apple_is_ripe
and with if/else
mark_apple if apple_is_ripe else leave_it_unmarked for apple in apple_box
One way:
def change(x):
if x is None:
return f(x)
else:
return ''
result = [change(x) for x in xs]
Although then you have:
result = map(change, xs)
Or you can use a lambda inline.
Here is another illustrative example:
>>> print(", ".join(["ha" if i else "Ha" for i in range(3)]) + "!")
Ha, ha, ha!
It exploits the fact that if i evaluates to False for 0 and to True for all other values generated by the function range(). Therefore the list comprehension evaluates as follows:
>>> ["ha" if i else "Ha" for i in range(3)]
['Ha', 'ha', 'ha']
[f(x) if x != None else '' for x in xs]
Syntax for list comprehension:
[item if condition else item for item in items]
[f(item) if condition else value for item in items]
[item if condition for item in items]
[value if condition else value1 if condition1 else value2]
The other solutions are great for a single if / else construct. However, ternary statements within list comprehensions are arguably difficult to read.
Using a function aids readability, but such a solution is difficult to extend or adapt in a workflow where the mapping is an input. A dictionary can alleviate these concerns:
xs = [None, 'This', 'is', 'a', 'filler', 'test', 'string', None]
d = {None: '', 'filler': 'manipulated'}
res = [d.get(x, x) for x in xs]
print(res)
['', 'This', 'is', 'a', 'manipulated', 'test', 'string', '']
It has to do with how the list comprehension is performed.
Keep in mind the following:
[ expression for item in list if conditional ]
Is equivalent to:
for item in list:
if conditional:
expression
Where the expression is in a slightly different format (think switching the subject and verb order in a sentence).
Therefore, your code [x+1 for x in l if x >= 45] does this:
for x in l:
if x >= 45:
x+1
However, this code [x+1 if x >= 45 else x+5 for x in l] does this (after rearranging the expression):
for x in l:
if x>=45: x+1
else: x+5
Make a list from items in an iterable
It seems best to first generalize all the possible forms rather than giving specific answers to questions. Otherwise, the reader won't know how the answer was determined. Here are a few generalized forms I thought up before I got a headache trying to decide if a final else' clause could be used in the last form.
[expression1(item) for item in iterable]
[expression1(item) if conditional1 for item in iterable]
[expression1(item) if conditional1 else expression2(item) for item in iterable]
[expression1(item) if conditional1 else expression2(item) for item in iterable if conditional2]
The value of item doesn't need to be used in any of the conditional clauses. A conditional3 can be used as a switch to either add or not add a value to the output list.
For example, to create a new list that eliminates empty strings or whitespace strings from the original list of strings:
newlist = [s for s in firstlist if s.strip()]
There isn't any need for ternary if/then/else. In my opinion your question calls for this answer:
row = [unicode((x or '').strip()) for x in row]
You can combine conditional logic in a comprehension:
ps = PorterStemmer()
stop_words_english = stopwords.words('english')
best = sorted(word_scores.items(), key=lambda x: x[1], reverse=True)[:10000]
bestwords = set([w for w, s in best])
def best_word_feats(words):
return dict([(word, True) for word in words if word in bestwords])
# with stemmer
def best_word_feats_stem(words):
return dict([(ps.stem(word), True) for word in words if word in bestwords])
# with stemmer and not stopwords
def best_word_feats_stem_stop(words):
return dict([(ps.stem(word), True) for word in words if word in bestwords and word not in stop_words_english])
# coding=utf-8
def my_function_get_list():
my_list = [0, 1, 2, 3, 4, 5]
# You may use map() to convert each item in the list to a string,
# and then join them to print my_list
print("Affichage de my_list [{0}]".format(', '.join(map(str, my_list))))
return my_list
my_result_list = [
(
number_in_my_list + 4, # Condition is False : append number_in_my_list + 4 in my_result_list
number_in_my_list * 2 # Condition is True : append number_in_my_list * 2 in my_result_list
)
[number_in_my_list % 2 == 0] # [Condition] If the number in my list is even
for number_in_my_list in my_function_get_list() # For each number in my list
]
print("Affichage de my_result_list [{0}]".format(', '.join(map(str, my_result_list))))
(venv) $ python list_comp.py
Affichage de my_list [0, 1, 2, 3, 4, 5]
Affichage de my_result_list [0, 5, 4, 7, 8, 9]
So, for you:
row = [('', unicode(x.strip()))[x is not None] for x in row]

Python if else within list comprehension [duplicate]

I have a list xs containing a mixture of strings and None values. How can I use a list comprehension to call a function on each string, but convert the None values to '' (rather than passing them to the function)?
I tried:
[f(x) for x in xs if x is not None else '']
but it gives a SyntaxError. What is the correct syntax?
See List comprehension with condition if you are trying to make a list comprehension that omits values based on a condition.
If you need to consider more than two conditional outcomes, beware that Python's conditional expressions do not support elif. Instead, it is necessary to nest if/else conditionals. See `elif` in list comprehension conditionals for details.
You can totally do that. It's just an ordering issue:
[f(x) if x is not None else '' for x in xs]
In general,
[f(x) if condition else g(x) for x in sequence]
And, for list comprehensions with if conditions only,
[f(x) for x in sequence if condition]
Note that this actually uses a different language construct, a conditional expression, which itself is not part of the comprehension syntax, while the if after the for…in is part of list comprehensions and used to filter elements from the source iterable.
Conditional expressions can be used in all kinds of situations where you want to choose between two expression values based on some condition. This does the same as the ternary operator ?: that exists in other languages. For example:
value = 123
print(value, 'is', 'even' if value % 2 == 0 else 'odd')
Let's use this question to review some concepts. I think it's good to first see the fundamentals so you can extrapolate to different cases.
Other answers provide the specific answer to your question. I'll first give some general context and then I'll answer the question.
Fundamentals
if/else statements in list comprehensions involve two things:
List comprehensions
Conditional expressions (Ternary operators)
1. List comprehensions
They provide a concise way to create lists.
Its structure consists of: "brackets containing an expression followed by a for clause, then zero or more for or if clauses".
Case 1
Here we have no condition. Each item from the iterable is added to new_list.
new_list = [expression for item in iterable]
new_list = [x for x in range(1, 10)]
> [1, 2, 3, 4, 5, 6, 7, 8, 9]
Case 2
Here we have one condition.
Example 1
Condition: only even numbers will be added to new_list.
new_list = [expression for item in iterable if condition == True]
new_list = [x for x in range(1, 10) if x % 2 == 0]
> [2, 4, 6, 8]
Example 2
Condition: only even numbers that are multiple of 3 will be added to new_list.
new_list = [expression for item in iterable if condition == True]
new_list = [x for x in range(1, 10) if x % 2 == 0 if x % 3 == 0]
> [6]
But howcome we have one condition if we use two if in new_list?
The prior expression could be written as:
new_list = [x for x in range(1, 10) if x % 2 and x % 3 == 0]
> [6]
We only use one if statement.
This is like doing:
new_list = []
for x in range(1, 10):
if x % 2 == 0 and x % 3 == 0:
new_list.append(x)
> [6]
Example 3
Just for the sake of argument, you can also use or.
Condition: even numbers or numbers multiple of 3 will be added to new_list.
new_list = [x for x in range(1, 10) if x % 2 == 0 or x % 3 == 0]
> [2, 3, 4, 6, 8, 9]
Case 3
More than one condition:
Here we need the help of conditional expressions (Ternary operators).
2.Conditional Expressions
What are conditional expressions? What the name says: a Python expression that has some condition.
<Exp1> if condition else <Exp2>
First the condition is evaluated. If condition is True, then <Exp1> is evaluated and returned. If condition is False, then <Exp2> is evaluated and returned.
A conditional expression with more than one condition:
<Exp1> if condition else <Exp2> if condition else <Exp3>...
An example from Real Python:
age = 12
s = 'minor' if age < 21 else 'adult'
> minor
The value of s is conditioned to age value.
3.List Comprehensions with Conditionals
We put list comprehensions and conditionals together like this.
new_list = [<Conditional Expression> for <item> in <iterable>]
new_list = [<Exp1> if condition else <Exp2> if condition else <Exp3> for <item> in <iterable>]
Condition: even numbers will be added as 'even', the number three will be added as 'number three' and the rest will be added as 'odd'.
new_list = ['even' if x % 2 == 0 else 'number three' if x == 3 else 'odd'
for x in range(1, 10)]
> ['odd', 'even', 'number three', 'even', 'odd', 'even', 'odd', 'even', 'odd']
The answer to the question
[f(x) for x in xs if x is not None else '']
Here we have a problem with the structure of the list: for x in xs should be at the end of the expression.
Correct way:
[f(x) if x is not None else '' for x in xs]
Further reading:
Does Python have a ternary conditional operator?
The specific problem has already been solved in previous answers, so I will address the general idea of using conditionals inside list comprehensions.
Here is an example that shows how conditionals can be written inside a list comprehension:
X = [1.5, 2.3, 4.4, 5.4, 'n', 1.5, 5.1, 'a'] # Original list
# Extract non-strings from X to new list
X_non_str = [el for el in X if not isinstance(el, str)] # When using only 'if', put 'for' in the beginning
# Change all strings in X to 'b', preserve everything else as is
X_str_changed = ['b' if isinstance(el, str) else el for el in X] # When using 'if' and 'else', put 'for' in the end
Note that in the first list comprehension for X_non_str, the order is:
expression for item in iterable if condition
and in the last list comprehension for X_str_changed, the order is:
expression1 if condition else expression2 for item in iterable
I always find it hard to remember that expression1 has to be before if and expression2 has to be after else. My head wants both to be either before or after.
I guess it is designed like that because it resembles normal language, e.g. "I want to stay inside if it rains, else I want to go outside"
In plain English the two types of list comprehensions mentioned above could be stated as:
With only if:
extract_apple for apple in apple_box if apple_is_ripe
and with if/else
mark_apple if apple_is_ripe else leave_it_unmarked for apple in apple_box
One way:
def change(x):
if x is None:
return f(x)
else:
return ''
result = [change(x) for x in xs]
Although then you have:
result = map(change, xs)
Or you can use a lambda inline.
Here is another illustrative example:
>>> print(", ".join(["ha" if i else "Ha" for i in range(3)]) + "!")
Ha, ha, ha!
It exploits the fact that if i evaluates to False for 0 and to True for all other values generated by the function range(). Therefore the list comprehension evaluates as follows:
>>> ["ha" if i else "Ha" for i in range(3)]
['Ha', 'ha', 'ha']
[f(x) if x != None else '' for x in xs]
Syntax for list comprehension:
[item if condition else item for item in items]
[f(item) if condition else value for item in items]
[item if condition for item in items]
[value if condition else value1 if condition1 else value2]
The other solutions are great for a single if / else construct. However, ternary statements within list comprehensions are arguably difficult to read.
Using a function aids readability, but such a solution is difficult to extend or adapt in a workflow where the mapping is an input. A dictionary can alleviate these concerns:
xs = [None, 'This', 'is', 'a', 'filler', 'test', 'string', None]
d = {None: '', 'filler': 'manipulated'}
res = [d.get(x, x) for x in xs]
print(res)
['', 'This', 'is', 'a', 'manipulated', 'test', 'string', '']
It has to do with how the list comprehension is performed.
Keep in mind the following:
[ expression for item in list if conditional ]
Is equivalent to:
for item in list:
if conditional:
expression
Where the expression is in a slightly different format (think switching the subject and verb order in a sentence).
Therefore, your code [x+1 for x in l if x >= 45] does this:
for x in l:
if x >= 45:
x+1
However, this code [x+1 if x >= 45 else x+5 for x in l] does this (after rearranging the expression):
for x in l:
if x>=45: x+1
else: x+5
Make a list from items in an iterable
It seems best to first generalize all the possible forms rather than giving specific answers to questions. Otherwise, the reader won't know how the answer was determined. Here are a few generalized forms I thought up before I got a headache trying to decide if a final else' clause could be used in the last form.
[expression1(item) for item in iterable]
[expression1(item) if conditional1 for item in iterable]
[expression1(item) if conditional1 else expression2(item) for item in iterable]
[expression1(item) if conditional1 else expression2(item) for item in iterable if conditional2]
The value of item doesn't need to be used in any of the conditional clauses. A conditional3 can be used as a switch to either add or not add a value to the output list.
For example, to create a new list that eliminates empty strings or whitespace strings from the original list of strings:
newlist = [s for s in firstlist if s.strip()]
There isn't any need for ternary if/then/else. In my opinion your question calls for this answer:
row = [unicode((x or '').strip()) for x in row]
You can combine conditional logic in a comprehension:
ps = PorterStemmer()
stop_words_english = stopwords.words('english')
best = sorted(word_scores.items(), key=lambda x: x[1], reverse=True)[:10000]
bestwords = set([w for w, s in best])
def best_word_feats(words):
return dict([(word, True) for word in words if word in bestwords])
# with stemmer
def best_word_feats_stem(words):
return dict([(ps.stem(word), True) for word in words if word in bestwords])
# with stemmer and not stopwords
def best_word_feats_stem_stop(words):
return dict([(ps.stem(word), True) for word in words if word in bestwords and word not in stop_words_english])
# coding=utf-8
def my_function_get_list():
my_list = [0, 1, 2, 3, 4, 5]
# You may use map() to convert each item in the list to a string,
# and then join them to print my_list
print("Affichage de my_list [{0}]".format(', '.join(map(str, my_list))))
return my_list
my_result_list = [
(
number_in_my_list + 4, # Condition is False : append number_in_my_list + 4 in my_result_list
number_in_my_list * 2 # Condition is True : append number_in_my_list * 2 in my_result_list
)
[number_in_my_list % 2 == 0] # [Condition] If the number in my list is even
for number_in_my_list in my_function_get_list() # For each number in my list
]
print("Affichage de my_result_list [{0}]".format(', '.join(map(str, my_result_list))))
(venv) $ python list_comp.py
Affichage de my_list [0, 1, 2, 3, 4, 5]
Affichage de my_result_list [0, 5, 4, 7, 8, 9]
So, for you:
row = [('', unicode(x.strip()))[x is not None] for x in row]

How Can I count the number of occurences for two items in a nested list

I have a nested list
a = [[1,'a','b'], [2,'c','d'], [3,'a','b']]
how can i count the number of occurrences that a & b appeared in the nested list?
in this case the answer shall be 2 times.
p.s. this is my first time post, so thanks for all the help.
You can test for inclusion in a list with
'a' in some_list
This will be true or false. You can make multiple tests with and (there are also some other ways that may be a little prettied):
'a' in some_list and 'b' in some_list
This will be true if both conditions are met. To do this for all the lists in your list you can use a list comprehension:
a_list = [[1,'a','b'], [2,'c','d'], [3,'a','b']]
['a' in x and 'b' in x for x in a_list]
This will return a list of boolean values, one for each item in your list:
[True, False, True]
When treated like numbers python treats True as 1 and False as 0. This means you can just sum that list to get you count and have a solution in one line:
a_list = [[1,'a','b'], [2,'c','d'], [3,'a','b']]
sum(['a' in x and 'b' in x for x in a_list])
# 2

Nested List -Python

I have two list . i want to compare with each other with the list index[1][2][3] of "a" of each list with other list index[1][2][3] of "b" .If its a match then ignore , if not then return the whole list.
a = [['Eth1/1/13', 'Marketing', 'connected', '10', 'full', 'a-1000'], ['Eth1/1/14', 'NETFLOW02', 'connected', '10', 'full', '100']]
b = [['Eth1/1/13', 'NETFLOW02', 'connected', '15', 'full', '100'], ['Eth1/1/14', 'Marketing', 'connected', '10', 'full', 'a-1000']]
Desired Output :
Diff a:
Eth1/1/14 NETFLOW02 connected 10 full 100
Diff b:
Eth1/1/13 NETFLOW02 connected 15 full 100
What i am trying :
p = [i for i in a if i not in b]
for item in p:
print item[0]
print "\n++++++++++++++++++++++++++++++\n"
q = [i for i in b if i not in a]
for item in q:
print item[0]
tried below but only managed to match index 1 of inner list , index 2 and 3 still need to be matched..
[o for o in a if o[1] not in [n[1] for n in b]
I am not getting the expected output.Any idea how to do this ?
for sublista in a:
if not any(sublista[1:4] == sublistb[1:4] for sublistb in b):
print(sublista)
You need an inner loop so that each sub-list from list a can be compared to each sub-list in list b. The inner loop is accomplished with a generator expression. Slices are used to to compare only a portion of the sub-lists. The built-in function any consumes the generator expression; it is lazy and will return True with the first True equivalency comparison. This will print each sub-list in a that does not have a match in b - to print each sub-list in b that does not have a match in a, put b in the outer loop and a in the inner loop.
Here is an equivalent Without using a generator expression or any:
for sublista in a:
equal = False
for sublistb in b:
if sublista[1:4] == sublistb[1:4]:
break
else:
print(sublista)
Sometimes it is nice to use operator.itemgetter so you can use names for the slices which can make the code more intelligible.:
import operator
good_stuff = operator.itemgetter(1,2,3)
for sublista in a:
if not any(good_stuff(sublista) == good_stuff(sublistb) for sublistb in b):
print(sublista)
itertools.product conveniently generates pairs and can be used as a substitute for the nested loops above. The following uses a dictionary (defaultdict) to hold comparison results for each sublist in a and b, then checks to see if there were matches - it does both the a to b and b to a comparisons.
import itertools, collections
pairs = itertools.product(a, b)
results = collections.defaultdict(list)
for sub_one, sub_two in pairs:
comparison = good_stuff(sub_one) == good_stuff(sub_two)
results[tuple(sub_one)].append(comparison)
results[tuple(sub_two)].append(comparison)
for sublist, comparisons in results.items():
if any(comparisons):
continue
print(sublist)
# or
from pprint import pprint
results = [sublist for sublist, comparisons in results.items() if not any(comparisons)]
pprint(results)
for v in a,b:
for items in v:
if 'NETFLOW02' in items:
print('\t'.join(items))
I'm not sure this is ok for your purpose but you seems to want to capture the results of a network interface called NETFLOW02 from these two lists.
I'm sure there's probably a reason this is unacceptable but you could also expand this to include other keywords in longer lists, well, any length of lists that are nested as far as explained in your question. To do this, you would need to create another list, hypothetically keywords = ['NETFLOW02','ETH01']
Then we simply iterate this list also.
results = []
for v in a,b:
for item in v:
for kw in keywords:
if kw in item:
results.append(item)
print('\t'.join(item))
print(results)

How to copy data in Python

After entering a command I am given data, that I then transform into a list. Once transformed into a list, how do I copy ALL of the data from that list [A], and save it - so when I enter a command and am given a second list of data [B], I can compare the two; and have data that is the same from the two lists cancel out - so what is not similar between [A] & [B] is output. For example...
List [A]
1
2
3
List [B]
1
2
3
4
Using Python, I now want to compare the two lists to each other, and then output the differences.
Output = 4
Hopefully this makes sense!
You can use set operations.
a = [1,2,3]
b = [1,2,3,4]
print set(b) - set(a)
to output the data in list format you can use the following print statement
print list(set(b) - set(a))
>>> b=[1,2,3,4]
>>> a=[1,2,3]
>>> [x for x in b if x not in a]
[4]
for element in b:
if element in a:
a.remove(element)
This answer will return a list not a set, and should take duplicates into account. That way [1,2,1] - [1,2] returns [1] not [].
Try itertools.izip_longest
import itertools
a = [1,2,3]
b = [1,2,3,4]
[y for x, y in itertools.izip_longest(a, b) if x != y]
# [4]
You could easily modify this further to return a duple for each difference, where the first item in the duple is the position in b and the second item is the value.
[(i, pair[1]) for i, pair in enumerate(itertools.izip_longest(a, b)) if pair[0] != pair[1]]
# [(3, 4)]
For entering the data use a loop:
def enterList():
result = []
while True:
value = raw_input()
if value:
result.append(value)
else:
return result
A = enterList()
B = enterList()
For comparing you can use zip to build pairs and compare each of them:
for a, b in zip(A, B):
if a != b:
print a, "!=", b
This will truncate the comparison at the length of the shorter list; use the solution in another answer given here using itertools.izip_longest() to handle that.

Categories

Resources