How to print a 1x2 list from 2 separate lists? - python

I need to print 2 entries from list 2 for every one entry in list 1
So say
ll = "1,2,3,4,5,6,7,8,9"
l2 = "a,b,c,d,e,f,g,h,i"
I need to print
1 a b
2 c d
3 d e
4 f g
5 h i
and so on
I can do
for i,j in zip(matches,matches2):
print (i,j)
but this just prints
1 a
2 b
3 c
4 d
but i can't work out how to print 2 entries from matches2 for every 1 entry in matches

You can create an iterator from matches2 so that it can be extracted twice for each iteration with zip:
iter2 = iter(matches2)
for i, j, k in zip(matches, iter2, iter2):
print(i, j, k)

Using your first example strings you can do something like this:
ll = "1,2,3,4,5,6,7,8,9".split(',')
l2 = "a,b,c,d,e,f,g,h,i".split(',')
for i in range(0,len(ll)):
j=i*2
if j+1<len(l2):
print(ll[i],l2[j],l2[j+1])

Related

Python nested for loop issues

I am trying to use a nested for loop to simply add two sets of numbers together respectively.
x=[1,2,3,4]
f=[0,1,2,3]
for i in x:
for j in f:
ans = i+j
ans2 = j
print(ans,ans2)
My output is
6 5
7 5
8 5
9 5
However, I want it to be
1 0
3 1
5 2
7 3
I'm not quite sure where i'm going wrong and any help would be appreciated.
You need to use the index into x to get the appropriate value of f to use as j. You can do this by iterating over the enumerated x:
x=[1,2,3,4]
f=[0,1,2,3]
for idx, i in enumerate(x):
j = f[idx]
ans = i+j
ans2 = j
print(ans,ans2)
Alternatively you could use zip and iterate both values at once:
for i, j in zip(x, f):
ans = i+j
ans2 = j
print(ans,ans2)
In both cases the output is:
1 0
3 1
5 2
7 3

create a iterate object with a group of tree from a iterate object in python

How can I create iterate group of three from a iterate object? For creating a pair of iteration function I can do something like
from itertools import tee
def func(iterate):
i, j = tee(iterate)
next(j, None)
return zip(i, j)
l = [1,2,3,4,5]
for a, b in func(l):
print(a, b)
> 1, 2
> 2, 3
> 3, 4
> 4, 5
You can expand on what you already did for groups of two, but with one more variable for the third item:
def func(iterate):
i, j, k = tee(iterate, 3)
next(j, None)
next(k, None)
next(k, None)
return zip(i, j, k)
l = [1,2,3,4,5]
for a, b, c in func(l):
print(a, b, c)
This outputs:
1 2 3
2 3 4
3 4 5
Note that your sample code in the question is incorrect as it is missing a call to zip in the returning value from func.
Use zip():
l = [1,2,3,4,5]
for a, b, c in zip(l, l[1:], l[2:]):
print(a, b, c)
# 1 2 3
# 2 3 4
# 3 4 5
You can also create groups of two with this method:
l = [1,2,3,4,5]
for a, b in zip(l, l[1:]):
print(a, b)
# 1 2
# 2 3
# 3 4
# 4 5

Optimizing pandas filter inside apply function

I have a list of pairs--stored in a DataFrame--each pair having an 'a' column and a 'b' column. For each pair I want to return the 'b's that have the same 'a'. For example, given the following set of pairs:
a b
0 c d
1 e f
2 c g
3 e h
4 i j
5 e k
I would like to end up with:
a b equivalents
0 c d [g]
1 e f [h, k]
2 c g [d]
3 e h [f, k]
4 i j []
5 e k [h, e]
I can do this with the following:
def equivalents(x):
l = pairs[pairs["a"] == x["a"]]["b"].tolist()
return l[1:] if l else l
pairs["equivalents"] = pairs.apply(equivalents, axis = 1)
But it is painfully slow on larger sets (e.g. 1 million plus pairs). Any suggestions how I could do this faster?
I think this ought to be a bit faster. First, just add them up.
df['equiv'] = df.groupby('a')['b'].transform(sum)
a b equiv
0 c d dg
1 e f fhk
2 c g dg
3 e h fhk
4 i j j
5 e k fhk
Now convert to a list and remove whichever letter is already in column 'b'.
df.apply( lambda x: [ y for y in list( x.equiv ) if y != x.b ], axis=1 )
0 [g]
1 [h, k]
2 [d]
3 [f, k]
4 []
5 [f, h]

Python: Iterate and Print Integer

In Java, we can do something like:
int i = 0;
while (i < 10)
System.out.println(i++);
where it iterates i and prints it. Can the same be done in python?
EDIT:
Specifically, I'd like to do something like:
words = ["red","green","blue"]
current_state = 0
for word in words:
for char in word:
print(char,current_state,current_state+1)
Result
r 0 1
e 1 2
d 2 3
g 3 4
r 4 5
e 5 6
....
If you want the equivalent of the ++ operator in Java, the answer is no. Python requires you to do:
i += 1
on its own line.
However, you may be looking for enumerate, which allows you to keep track of what index you are at while iterating over a container:
>>> for i, j in enumerate(['a', 'b', 'c', 'd']):
... print(i, j)
...
0 a
1 b
2 c
3 d
>>>
i = 0
while i < 10:
i += 1
print i

pythonic way for nested loops checking items against two or more list

I want to check items against two lists in python which are again put in the one big list
In my codes , combinedList is big list and row1 and row2 are sub-list.
I need to check items in row1 and row2 against each other. I got rough idea in psudo code however , since i m new to python . is there any good codes for checking against two list for their item without repeating the same pair more than once?
row1 = [a,b,c,d,....]
row2 = [s,c,e,d,a,..]
combinedList = [row1 ,row2]
for ls in combinedList:
**for i=0 ; i < length of ls; i++
for j= i+1 ; j <length of ls; j++
do something here item at index i an item at index j**
I guess you're looking for itertools.product:
>>> from itertools import product
>>> row1 = ['a', 'b', 'c', 'd']
>>> row2 = ['s', 'c', 'e', 'd', 'a']
>>> seen = set() #keep a track of already visited pairs in this set
>>> for x,y in product(row1, row2):
if (x,y) not in seen and (y,x) not in seen:
print x,y
seen.add((x,y))
seen.add((y,x))
...
a s
a c
a e
a d
a a
b s
b c
b e
b d
b a
c s
c c
c e
c d
d s
Update:
>>> from itertools import combinations
>>> for x,y in combinations(row1, 2):
... print x,y
...
a b
a c
a d
b c
b d
c d
Use the zip() built-in function to pair values of two lists:
for row1value, row2value in zip(row1, row2):
# do something with row1value and row2value
If you wanted to combine each element from row1 with each element of row2 instead (the product of the two lists), use itertools.product() instead:
from itertools import product
for row1value, row2value in product(row1, row2):
# do something with row1value and row2value
zip() simply pairs up the lists producing len(shortest_list) items, product() pairs up each element in one list with each element in the other, producing len(list1) times len(list2) items:
>>> row1 = [1, 2, 3]
>>> row2 = [9, 8, 7]
>>> for a, b in zip(row1, row2):
... print a, b
...
1 9
2 8
3 7
>>> from itertools import product
>>> for a, b in product(row1, row2):
... print a, b
...
1 9
1 8
1 7
2 9
2 8
2 7
3 9
3 8
3 7

Categories