I'm cross-referencing two lists to find which items coincide between the two lists. The first list orig is 32 items in size, and I'm cross-referencing it with a much-larger list sdss which is 112,000 items in size. So far this is what I've got:
for i in range(0,len(orig),1):
if orig[i] in sdss:
print('\n %s' % (orig[i]))
This gives me the items that are the same between the two lists, however, how would I efficiently return the indices (or location) of cross-referenced items inside of the sdss list (the larger list)?
EDIT: I guess I should've been clearer. I am actually cross-referencing two arrays with ints, not strings.
If the order is not of importance you can use set intersection to find the unique common elements and list comprehension to get the index and element as tuple
[(sdss.index(common_element),common_element) for common_element in set(orig) & set(sdss)]
Note that "index" raises ValueError if the value is not found in the list but in this case the value WILL exist in sdss. So, no need to worry about nonexistent elements throwing errors.
You can also use numpy.intersect1d
You can use .find() which gives the index of an item in a list, but returns -1 on failure:
for item in orig:
index = sdss.find(item)
if index != -1:
print("\n %d" % index)
I modified how you iterated because you don't need the index in orig; you need each item. BTW, you could have used range(len(orig)) because your start and step arguments are already the defaults.
Related
Is there a way to print an individual item from a set? In the same way which you would print items of a list by referencing values between 0 and size of the list.
I was trying to reference items by using print(set_name[i]). But was receiving an error for trying to reference an item in this way. I was able to print the full set with print(set(name_set)), so there was not an issue with defining the values.
Indexing is not supported in set. If you want to get an element from a set, you should either cast it to list (Note that set is unordered), or use an iterator:
for element in <YOUR_SET>:
if element == <DESIRED_VALUE>:
break
print(element)
I have a list where each element is of the form [list of integers, integer].
For example, an element of the list may look like this [[1,3,1,2], -1].
I want to sort a list containing the described type of elements by the following criteria:
if the integer lists of two elements (i.e. element[0]) are of different length, the element with the smaller integer list is the smaller one.
else if the integer lists are of the same length, the smaller element is that which has the smaller integer for the first integer which differs in the integer list of both elements. For example:
[[1,1,99,100], -1] < [[1,1,100,1], -1], because 99 < 100.
else if the integer lists are identical, the smaller element is the one with the smaller integer in element[1].
How would I write an approriate key function I could pass to sorted() or sort()?
List the three criteria in your key:
sorted(inputlist, key=lambda e: (len(e[0]), e[0], e[1]))
Now you are sorting each element first by the length, then by comparing the first element directly (which in only used when the first element is of equal length), then by the value of the last integer.
Python sorts tuples and lists like these lexicographically; compare the first element, and only if that doesn't differ, compare the second element, etc.
The second element here is e[0] which will only be used if both compared entries have nested lists of equal length. These are again compared lexicographically, so pairing up elements until a pair differs.
key = lambda x: (len(x[0]), x[0], x[1])
This works because tuples (and lists) are compared by looking at each element in turn until a difference is found. So when you want to sort on multiple criteria in order of preference, just stick each criterion into an element of a tuple, in the same order.
I'm assuming that by "smaller" you mean the same thing as "lesser", that is to say you don't mean to compare absolute values.
I'm getting this error: index out of range, in if largerList[j] == smallerList[i]. I'm working on an assignment about binary search trees, I put the trees into lists and I'm just trying to compare the two lists:
def matchList(largerList, smallerList) :
matches = []
for i in smallerList:
for j in largerList:
if largerList[j] == smallerList[i] :
matches[i] = smallerList[i]
return matches
I'm assuming nested for loops should totally iterate all elements in each loop, so smallerList is the smaller list so smallerList doesn't make largerList go out of bounds. The inner for-loop should iterate over all of the larger list entirely, comparing each value to each element of the smaller list. Why doesn't it work?
You can't set a list value with matches[i] if that index does not exist in matches.
Try appending instead:
Change this matches[i] = smallerList[i] to this matches = matches.append(smallerList[i])
Trying to find matching elements in lists like this is rather inefficient. One thing you could improve to make it arguably more pythonic is to use a list comprehension:
matches = [i for i in largerList if i in smallerList]
But then the more mathematically sensible approach still would be to realise that we have two sets of elements and we want to find an intersection of two sets so we can write something like:
matches = set(largerList).intersection(smallerList)
I have a 3d list 6 items long and 6 items wide, which is a list of lists of a list of strings.
lst = [ [['A'],['A'],['B'],['B'],['A'],['A']],
[['B'],['B'],['A'],['A'],['B'],['B']],
[['A'],['A'],['B'],['B'],['A'],['A']],
[['B'],['B'],['A'],['A'],['B'],['B']],
[['A'],['A'],['B'],['B'],['A'],['A']],
[['B'],['B'],['A'],['A'],['B'],['B']],
]
I want to move the strings into other locations on the list, but I know I'm not using the right code:
lst.insert([1][0][0], 'A')
gives me a TypeError: 'int' object is not subscriptable
I know how to add items by doing this:
lst2 = lst[0][0]
lst2.append('A')
(adds another 'A' string to the first item)
I want to perform various actions on the lowest list like:
add/remove strings to that list,
check how many string items are in that list
move 'A' or 'B' strings to different locations so that they have multiple strings.
Check to see what the first string is in the list is
I am very new to programming and I am just starting to understand how to use 2d lists.
How do I accomplish this without any additional modules or libraries?
First of all, let me clarify this line:
lst.insert([1][0][0], 'A')
The insert method expects an int argument for the index. If you want to insert an element in a multidimensional list it should be done as:
lst[1][0].insert(0, 'A')
After all, it is a list of list (of lists). Only if you look at an inner index (defined by 2 coordinates), will you get a simple list (of strings in this case). You can then insert a string element to this simple list, by calling the insert() method.
check how many string items are in that list
count = 0
for d2 in lst: #d2 is a 2d list (an element of a 3d list)
for d1 in d2: # d1 - 1 dimensional
count += len(d1)
Here, I have gone through each of the lowermost-level (simple) lists using a nested loop, counted how many elements are there in each and added them up.
move 'A' or 'B' strings to different locations so that they have multiple strings.
Say I want to move the element from [3][2][0] to [1][2][1]. I would insert it in the new position and then delete from the old.
element = lst[3][2][0] # the task can be accomplished without using another variable, but this is for better understanding
lst[1][2].insert(1, element) # inserting
lst[3][2].pop(0) # deleting
The element could even be moved to a position like [1][2]. So there would be one string along with the other 'sub-lists'
Check to see what the first string is in the list is
Do you mean lst[0][0][0].
I have a list where each element is of the form [list of integers, integer].
For example, an element of the list may look like this [[1,3,1,2], -1].
I want to sort a list containing the described type of elements by the following criteria:
if the integer lists of two elements (i.e. element[0]) are of different length, the element with the smaller integer list is the smaller one.
else if the integer lists are of the same length, the smaller element is that which has the smaller integer for the first integer which differs in the integer list of both elements. For example:
[[1,1,99,100], -1] < [[1,1,100,1], -1], because 99 < 100.
else if the integer lists are identical, the smaller element is the one with the smaller integer in element[1].
How would I write an approriate key function I could pass to sorted() or sort()?
List the three criteria in your key:
sorted(inputlist, key=lambda e: (len(e[0]), e[0], e[1]))
Now you are sorting each element first by the length, then by comparing the first element directly (which in only used when the first element is of equal length), then by the value of the last integer.
Python sorts tuples and lists like these lexicographically; compare the first element, and only if that doesn't differ, compare the second element, etc.
The second element here is e[0] which will only be used if both compared entries have nested lists of equal length. These are again compared lexicographically, so pairing up elements until a pair differs.
key = lambda x: (len(x[0]), x[0], x[1])
This works because tuples (and lists) are compared by looking at each element in turn until a difference is found. So when you want to sort on multiple criteria in order of preference, just stick each criterion into an element of a tuple, in the same order.
I'm assuming that by "smaller" you mean the same thing as "lesser", that is to say you don't mean to compare absolute values.