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])
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 been given two lists, say list1 and list2. I have to arrange the elements of the list1 in such a way that at particular index the element of list1 is greater than the element of list2. We have to find how many such elements of list1 are there.
For example:
list1=[20,30,50]
list2=[60,40,25]
Here only element index 2 is greater i.e. 50>25, but if we swap 50 and 30 in list1
So,
list1=[20,50,30]
list2=[60,40,25]
then 50 > 40 ( at index 1) and 30 > 25 (at index 2). So we got 2 elements 50 and 30 which are greater at their respective index.
Here is my approach
def swap(a,b):
a,b=b,a
return a,b
n=3
g=list(map(int,input().split()))
o=list(map(int,input().split()))
c=0
for i in range(n):
if o[i]>g[i]:
for j in range(i+1,n):
if g[j]>o[i]:
g[i],g[j]=swap(g[i],g[j])
c+=1
break
else:
c+=1
print(c)
But for
list1= [3,6,7,5,3,5,6,2,9,1]
list2= [2,7,0,9,3,6,0,6,2,6]
Its giving c=6 but expected output is c=7
You have to sort the two lists and then run through them to find "matches" where a value of list1 is greater than the next value of list2. This will pair up the values with the smallest possible difference and thus maximize the pairings.
For example:
list1=[20,30,50]
list2=[60,40,25]
iter1 = iter(sorted(list1)) # iterator to run through sorted list1
n1 = next(iter1,None) # n1 is current number in list1
count = 0 # count of paired elements (n1>n2)
for n2 in sorted(list2): # go through sorted list 2
while n1 is not None and n1 <= n2: # skip over ineligible items of list1
n1 = next(iter1,None)
if n1 is None: break # stop when list 1 is exhausted
count += 1 # count 1 pair and move on to next of list2
print(count) # 2
list1= [3,6,7,5,3,5,6,2,9,1]
list2= [2,7,0,9,3,6,0,6,2,6]
list1 = sorted(list1)
it = iter(enumerate(list1))
list2 = sorted(list2)
c = next(it)
good = []
for i, n in enumerate(list2 ):
try:
while c[1] < n:
c = next(it)
good.append([i, c[0]])
c = next(it)
except StopIteration:
break
for idx1, idx2 in good:
list1[idx1], list1[idx2] = list1[idx2], list1[idx1]
final_l1_l2 = sum(a > b for a, b in zip(list1, list2))# how many l1 are > l2
print(final_l1_l2)
output:
7
also, you can print list1 and list2 after the rearrange:
print(list1)
print(list2)
output:
[1, 2, 3, 3, 5, 6, 6, 7, 9, 5]
[0, 0, 2, 2, 3, 6, 6, 6, 7, 9]
the idea is to sort both lists and then to check what elements from list1 are greater than the elements from list2 if one element from list1 it is smaller then the current element from list2 just go to the next element from the list1 till there are no more elements in list1
I want to create 2 lists (list1 with values equal to zero and list 2 with values greater than zero) using a list of tuples (based on its first element). Following is what I am using:
a=[(1.2,'197301'),(0,'19980101'),(10,'19010101'),(0,'19830101')]
list1 = [a for a in a if a == 0]
list2 = [a for a in a if a != 0]
list1 gives [(0, '19980101'), (0, '19830101')] but list2 returns: TypeError: 'int' object is not iterable. Any suggestion?
You are redefining a during your list comprehension:
>>> a=[1.2,'19730101',0,'19980101',10,'19910101',0,'19830101']
>>> list1 = [a for a in a if a == 0]
>>> a
'19830101'
Works great if you change the variable:
>>> list1 = [i for i in a if i == 0]
>>> list2 = [i for i in a if i != 0]
>>> list1
[0, 0]
>>> list2
[1.2, '19730101', '19980101', 10, '19910101', '19830101']