Loop Character A/b Alternately
How can I print A/B character alternately in python loop? What I expect in result: oneA twoB threeA fourB ...
Solution 1:
You can use itertools.cycle
to repeat through a sequence. This is typically used with zip
to iterate through a longer list, while repeating the shorter one. For example
import itertools
for i,j inzip(['one', 'two', 'three', 'four'], itertools.cycle('AB')):
print(i+j)
Output
oneA
twoB
threeA
fourB
Solution 2:
try this:
l1 = ['A','B']
l2 = ['one','two','three','four']
for i,val inenumerate(l2):
print(val + l1[i%len(l1)])
Solution 3:
You could also try using the modulus operator % on the index of an incremented for loop for the numbers to alternate the letters:
list_num = ['one', 'two', 'three', 'four', 'five', 'six']
list_alpha = ['A', 'B']
list_combined = []
for i in range(0, len(list_num)):
list_combined.append(list_num[i] + (list_alpha[1] if i % 2else list_alpha[0]))
list_combined
>>> ['oneA', 'twoB', 'threeA', 'fourB', 'fiveA', 'sixB']
Solution 4:
Something like:
alternate_words = ['A', 'B']
count = 0while count < 5:
print count+1, alternate_words[count % len(alternate_words)]
count += 1
Output:
1 A
2 B
3 A
4 B
5 A
Solution 5:
I think this will help ->
a1 = ['A','B']
a2 = ['one','two','three','four']
for i in range(len(a2)):
print a2[i]+a1[i%2]
Post a Comment for "Loop Character A/b Alternately"