Related
l = ['foo','bar','baz']
l2 = ['xbary', 'uobazay', 'zzzfooaa']
How can I get the position of the strings in l that appear in l2?
p = [1,2,0] #because bar is in index 1 of l, baz in index 2 and foo in index 0
You could use a double for-loop where the inner loop enumerate over l to get the indices:
out = [i for item2 in l2 for i, item1 in enumerate(l) if item1 in item2]
Output:
[1, 2, 0]
You can also try:
res = [i for elem in l2 for i in range(len(l)) if l[i] in elem]
print(res)
Output:
[1, 2, 0]
This question already has answers here:
Finding the index of an item in a list
(43 answers)
Closed 1 year ago.
Let's say I have two lists
a = [1,2,3,4]
b = [5,9,1,2]
and I want to get the indices of every element in list b when an element of list a is in there. In this example, the result should be a list c containing all indices in b
c = [2,3]
1 in list a is on index 2 in b
2 in list a is on index 3 in b
Thanks in advance!!
[index for (index, item) in enumerate(b) if item in a]
output
[2, 3]
Use this:
c = [b.index(x) for x in a if x in a and x in b]
c
Output:
[2, 3]
I would solve that this way:
a = [1, 2, 3, 4]
b = [5, 9, 1, 2]
b_d = {b[i]: i for i in range(len(b))}
result = [b_d[v] for v in a if v in b_d]
print(result)
Using a set will make the inclusion check faster:
set_a = set(a)
c = [i for i, x in enumerate(b) if x in set_a]
You could simply iterate over the first list, then check if the item is inside the second list, if yes then append the index to your new list c:
a = [1,2,3,4]
b = [5,9,1,2]
c = []
for item in list_a:
if item in list_b:
c.append(list_b.index(item))
print(c)
Or use a list comprehension:
[list_b.index(item) for item in list_a if item in list_b]
So lets say I have two lists a=[1,2,3,4,5,6] and b=[2,34,5,67,5,6] I want to create a third list which will have 1 where elements are different in a and b and 0 when they are same, so above would be like c=[1,1,1,1,0,0]
You can zip the lists and compare them in a list comprehension. This takes advantage of the fact that booleans are equivalent to 1 and 0 in python:
a=[1,2,3,4,5,6]
b=[2,34,5,67,5,6]
[int(m!=n) for m, n, in zip(a, b)]
# [1, 1, 1, 1, 0, 0]
Try a list comprehension over elements of each pair of items in the list with zip:
[ 0 if i == j else 1 for i,j in zip(a,b) ]
Iterating with a for loop is an option, though list comprehension may be more efficient.
a=[1,2,3,4,5,6]
b=[2,34,5,67,5,6]
c=[]
for i in range(len(a)):
if a[i] == b[i]:
c.append(0)
else:
c.append(1)
print(c)
prints
[1, 1, 1, 1, 0, 0]
If you will have multiple vector operations and they should be fast. Checkout numpy.
import numpy as np
a=[1,2,3,4,5,6]
b=[2,34,5,67,5,6]
a = np.array(a)
b = np.array(b)
c = (a != b).astype(int)
# array([1, 1, 1, 1, 0, 0])
idk if this is exactly what youre loocking for but this should work:
edidt: just found out that Joe Thor commented almost the exact same a few minutes earlier than me lmao
a = [1, 2, 3, 4, 5, 6]
b = [2, 34, 5, 67, 5, 6]
results = []
for f in range(0, len(a)):
if a[f] == b[f]:
results.append(0)
else:
results.append(1)
print(results)
This can be done fairly simply using a for loop. It does assume that both lists, a and b, are the same length. An example code would like something like this:
a = [1,2,3,4,5,6]
b = [2,34,5,67,5,6]
c = []
if len(a) == len(b):
for i in range(0,len(a)):
if(a[i] != b[i]):
c.append(1)
else:
c.append(0)
This can also be done using list comprehension:
a = [1,2,3,4,5,6]
b = [2,34,5,67,5,6]
c = []
if len(a) == len(b):
c = [int(i != j) for i,j in zip(a,b)]
The list comprehension code is from this thread: Comparing values in two lists in Python
a = [1, 2, 3, 4, 5, 6]
b = [2, 34, 5, 67, 5,6]
c = []
index = 0
x = 1
y = 0
for i in range(len(a)): # iterating loop from index 0 till the last
if a[index]!= b[index]: # comapring each index
c.append(x) # if not equal append c with '1'
index += 1 # increment index to move to next index in both lists
else:
c.append(y)
index += 1
print(c)
This should work for two lists of any type.
tstlist = ["w","s","u"]
lstseasons = ["s","u","a","w"]
lstbool_Seasons = [1 if ele in tstlist else 0 for ele in lstseasons]
Output: lstbool_Seasons = [1,1,0,1]
This is the first time I have posted anything, still figuring out how things work here, so please forgive faux pas...
I have two lists, let's say
list1 = [1,2,3,4,5,6,7]
list2 = ["A", "B", "C"]
The condition is, that "A" in list2 relates to first 2 numbers in list1, "B" - to the next to numbers, "C" - to the all left numbers.
I try to create loop for these two lists so that as a result I could get the following:
1, A
2, A
3, B
4, B
5, C
6, C
7, C
I thought of using "for i in list1[:n]" construction where n - number of elements, but I cannot predefine n since the amount of elements in list1 that belong to the last element in list2 is unknown.
Here is my attempt:
s=0
n=2
for i in l1:
for t in l2[s:n]:
print (i,t)
s+=2
n+=2
You can use list comprehension to achieve that:
n = 2
# this is just the known length
res = [(y, x) for i, x in enumerate(list2) for y in list1[n*i:n*i+n]]
# just add the remaining items
res += [(x, list2[-1]) for x in list1[n*len(list2):]]
for x in res:
print(x)
list1 = [1,2, 3,4, 5,6,7]
list2 = ["A", "B", "C"]
items_to_iterate_on_list1_for_each_in_list2 = 2
index1 = 0
for item2 in list2:
# We iterate for each element in list 2
# on two elements of list 1
for offset in range(items_to_iterate_on_list1_for_each_in_list2):
print(f'{list1[index1 + offset]}, {item2}')
index1 += items_to_iterate_on_list1_for_each_in_list2
# If there are elements remaining in list1, we iterate over them with last element of list2
for i in range(index1, len(list1)):
print(f'{list1[i]}, {item2}')
Try the following code :
list1 = [1,2,3,4,5,6,7]
list2 = ["A", "B", "C"]
for j,i in enumerate(list1):
if j<2: print(list2[0],',',i)
elif j<4: print(list2[1],',',i)
else : print(list2[2],',',i)
You could make a list of index ranges that are to be used with slicing, and you can have None meaning the end of the list, so that the last slice is just however many items are left:
list1 = [1,2,3,4,5,6,7]
list2 = ["A", "B", "C"]
ranges = [(0, 2), (2, 4), (4, None)]
for r, letter in zip(ranges, list2):
for i in list1[slice(*r)]:
print(f'{i}, {letter}')
This gives
1, A
2, A
3, B
4, B
5, C
6, C
7, C
Solution similiar to your code:
list1 = [1,2, 3,4, 5,6,7]
list2 = ["A", "B", "C"]
items_to_iterate_on_list1_for_each_in_list2 = 2
s=0
n=2
for index2, item2 in enumerate(list2):
index1 = index2 * n
for t in list1[index1:index1 + n]:
print(f'{t}, {item2}')
# Adjust to last index1
index1 += n
# If there are elements remaining in list1, we iterate over them with last element of list2
for i in range(index1, len(list1)):
print(f'{list1[i]}, {item2}')
Another way of doing it is
list1 = [1,2,3,4,5,6,7]
list2 = ["A", "B", "C"]
for i in range(len(list1)):
index = min(i // 2, 2)
print(f"{list1[i]}, {list2[index]}")
As far as I can understand, you want to associate each item of list2 with every 2 items from list1. In case where the number of elements in list1 is more than 6, any element after 6th position (or index 5) will be associated with the last element of list2. Here is my approach:
list1 = [1,2,3,4,5,6,7,8,9]
list2 = ["A", "B", "C"]
for item in list1:
try:
print(item, list2[list1.index(item)//2])
except:
print(item, list2[-1])
def first_and_last(list_1):
new_list = [i for i in list_1 if i ==(list_1[0] or list_1[len(list_1 - 1)])]
return new_list
after i enter the sequence of numbers, the output stays the same as the original list. I think there would be something wrong with my list comprehension
a= [input("Enter a sequence of numbers separated by commas :")]
b = first_and_last(a)
print (b)
There are two problems that i have found:
1)
a = [input("Enter a sequence of numbers separated by commas :")]
This will give you a list containing the entire string as a single element, but not individual elements. For example, on executing this string you will get...
a = ['1,2,3,4,5']
to resolve this you need take the string input and split it on ","
a = input("Enter a sequence of numbers separated by commas :").split(",")
2)
The conditional filter used in list comprehension is wrong..
2 or 3 = 2
3 or 2 = 3
0 or 2 = 2
2 or 0 = 2
If there is a "0" element it returns the other non zero element, if both are non zero it returns the first one, hence
if my list was...
a = [1 , 2 , 3]
b = first_and_last(a)
print(b)
this would result in
b = [3]
Hence the right condition or approach would be
new_list = [i for i in list_1 if i == list_1[0] or i == list_1[len(list_1 - 1)]]
or
b = list()
b.append(a[0])
b.append(a[len(a)-1])
The following output of my python console might already clarify a few things:
>>> new_list = [input()]
1, 2, 3, 4
>>> new_list
[(1, 2, 3, 4)]
>>> l = [i for i in new_list if i==(new_list[0] or new_list[-1])]
>>> l
[(1, 2, 3, 4)]
>>> new_list[-1]
(1, 2, 3, 4)
You have a list, but your list a has only one element. In my example, a only contains the element (1, 2, 3, 4).
When you do your list comprehension, you take the element iff it equals the first or last element - which it does. And there's no error because the index -1 just stands for the last element in your list.
You can turn the input tuple into a list:
>>> list(input())
1, 2, 3, 4
[1, 2, 3, 4]
Then, your list comprehension could work.
I'm not sure if your syntax for the if works though. I would go with
>>> li = list(input())
1, 2, -3, 4
>>> new_list = [i for i in li if (li[0]==i or i==li[-1])]
>>> new_list
[1, 4]
>>> lix = list(input())
1, 1, 2, 3, 4, 2
>>> other_list = [i for i in lix if (lix[0]==i or i==lix[-1])]
>>> other_list
[1, 1, 2, 2]
If you use your if syntax, what you're testing is whether a element equals (li[0] or li[-1]). I believe that this will always either be 0 or 1, because it is a boolean expression.
>>> other_list = [i for i in lix if i==(lix[0] or lix[-1])]
>>> other_list
[1, 1]
I tested this in python 2.7.14 so your syntax might vary slightly.
You need to split the string into a list.
You can simplify your condition.
Code:
def first_and_last(input):
list = input.split(',')
match = list[0], list[-1]
return [i for i in list if i in match]