Checking if list is a sublist
i need to check if list1 is a sublist to list2 (True; if every integer in list2 that is common with list1 is in the same order of indexes as in list1)
Your code isn't working because as soon as a list element in ls1 doesn't occur in ls2 it will return False immediately.
This creates two lists that contain only the common elements (but in their original order) and then returns True when they are the same:
def sublist(lst1, lst2):
ls1 = [element for element in lst1 if element in lst2]
ls2 = [element for element in lst2 if element in lst1]
return ls1 == ls2
edit: A memory-efficient variant:
def sublist(ls1, ls2):
'''
>>> sublist([], [1,2,3])
True
>>> sublist([1,2,3,4], [2,5,3])
True
>>> sublist([1,2,3,4], [0,3,2])
False
>>> sublist([1,2,3,4], [1,2,5,6,7,8,5,76,4,3])
False
'''
def get_all_in(one, another):
for element in one:
if element in another:
yield element
for x1, x2 in zip(get_all_in(ls1, ls2), get_all_in(ls2, ls1)):
if x1 != x2:
return False
return True
Check if list is sublist of another list and the elements are in the same order
This will check all subList of length a and return True if a is found in b
Not sure about order :
def isSublist(a,b):
#checking all unique elements and their count
for i in set(a):
if i not in b or a.count(i) > b.count(i):
return False
return True
Sure about order :
def isSublist(a,b):
for i in range(len(b)-len(a)+1):
if b[i:i+len(a)] == a:
return True
return False
How to check if a list partially matches one of the lists in a list of lists?
Below example works by:
- Iterating over each sublist within
lol
- Generating a list representing the intersection of the current sublist and
lol
(stored each iteration astemp
) - Comparing
sorted()
versions oftemp
andl
, returningTrue
if a match is found. - Returning
False
if all sublists are checked with no match found
The function will return True
if either a full match is found between elements of l
and any sublist of lol
, or in "partial match" cases in which all elements of l
are present within any sublist of lol
.
def compare_sublists(l, lol):
for sublist in lol:
temp = [i for i in sublist if i in l]
if sorted(temp) == sorted(l):
return True
return False
How to check if an element is in a sub list, then print the sub list
As the correct answer as been pointed out by @Jab already, I'll correct your mistake so that it helps with your homework assignment
In your code from line 9 to line 13:
for lists in list_of_lists:
if search in lists:
output = lists
print('The available flights are:', *output, sep='\n')
lists variable will be equal to :
[1] MH371, MALAYSIAN AIRLINE, KUALA LUMPUR, BEIJING , 19-12-2021, N/A
in the first run and your really searching for the list of strings instead of just a string like "KUALA LUMPUR"
So, to correct that you can use 2 loops instead of one to access the inner elements.
like this :
for lists in list_of_lists:
for elements in lists:
if search in elements:
output = lists
print('The available flights are: \n', *output, sep='')
Check for presence of a sublist in list with order kept, and allow wildcards
One way is to use all
when checking against sublists and an if
that skips asterisks:
def my_func(a_list, sub_list):
n = len(sub_list)
# list-level comparison is now via element-wise
return any(all(sub_item == chunk_item
for sub_item, chunk_item in zip(sub_list, a_list[i:i+n])
if not np.isnan(sub_item)) # "is_not_asterisk" condition
for i in range(len(a_list)-n+1))
where I used not np.isnan(...)
as the asterisk condition as mentioned in the question; but it could be many things: e.g., if asterisk is literally "*"
in sublists, then the condition there is changed to if sub_item != "*"
.
sample with np.nan
as asterisk:
for a_list in my_lists:
if my_func(a_list, [np.nan, np.nan, 0, 0, 0, 1, np.nan]):
print(a_list)
gives
[1, 1, 1, 1, 0, 2, 1, 2, 1, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 0]
[1, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0]
all
returns True
if the iterable is empty so if an all-asterisk sub-list is passed, it will return True
for all candidates (as long as their length permits, which any
will handle because any
with empty iterable is False
!).
Check if sublist is in list in the same order
This is not the most correct code but it works!
public static boolean subList(char[] list, char[] sublist) {
int subposition = 0;
boolean subarray = false;
for (int i = 0; i < list.length; i++) {
if (subposition < sublist.length) {
if (list[i] == sublist[subposition]) {
subposition++;
} else if (subposition > 0) {
subposition = 0;
i--;
}
if(subposition == sublist.length) {
subarray = true;
}
}
}
return subarray;
}
How can I verify if one list is a subset of another?
Use set.issubset
Example:
a = {1,2}
b = {1,2,3}
a.issubset(b) # True
a = {1,2,4}
b = {1,2,3}
a.issubset(b) # False
The performant function Python provides for this is set.issubset
. It does have a few restrictions that make it unclear if it's the answer to your question, however.
A list may contain items multiple times and has a specific order. A set does not. Additionally, sets only work on hashable objects.
Are you asking about subset or subsequence (which means you'll want a string search algorithm)? Will either of the lists be the same for many tests? What are the datatypes contained in the list? And for that matter, does it need to be a list?
Your other post intersect a dict and list made the types clearer and did get a recommendation to use dictionary key views for their set-like functionality. In that case it was known to work because dictionary keys behave like a set (so much so that before we had sets in Python we used dictionaries). One wonders how the issue got less specific in three hours.
Related Topics
How to Set the Aspect Ratio in Matplotlib
Check If a String in a Pandas Dataframe Column Is in a List of Strings
How to Switch to the Active Tab in Selenium
Can Python Pickle Lambda Functions
What Does a for Loop Within a List Do in Python
How to Redirect Stdout and Stderr to Logger in Python
Python: Simple List Merging Based on Intersections
Python - Is a Dictionary Slow to Find Frequency of Each Character
Coalesce Values from 2 Columns into a Single Column in a Pandas Dataframe
Cleanest Way to Get Last Item from Python Iterator
How to Create a Custom Activation Function with Keras
Difference Between Methods and Functions, in Python Compared to C++
Python Argparse Mutual Exclusive Group
Grouping/Clustering Numbers in Python
When Would the -E, --Editable Option Be Useful with Pip Install