Python, toggle variables in a script - python

I've got a script running that I want to toggle between different variables.
Let's say I've got a list of urls and I want to concatenate one of the variables a, b or c. I don't care which but I'd expect the variables to repeat but the list would run through once.
v would end up looking like
url1+string1
url2+string2
url3+string3
url4+string1
url5+string2
etc
def function1():
list = [url1,url2,url3,url4,url5.......]
a = 'string1'
b = 'string2'
c = 'string3'
for i in list:
v = i+(a then b then c then a then b then c)
I was able to get this to work on my own but I'm new and learning, does anyone have a more elegant solution to this?
a = 'a'
b = 'b'
c = 'c'
list1 = ['string1','string2','string3','string4','string5','string6','string7','string8']
list2 = [a, b, c]
c = 0
for i in list1:
if c == len(list2):
c = 0
vv = i + list2[int(c)]
c = c + 1
print vv
it returns what I was looking for but it's messy:
string1a
string2b
string3c
string4a
string5b
string6c
string7a
string8b

You can utilise itertools.cycle to repeat one of the iterables, eg:
from itertools import cycle, izip
list1 = ['string1','string2','string3','string4','string5','string6','string7','string8']
list2 = ['a', 'b', 'c']
for fst, snd in izip(list1, cycle(list2)):
print fst + snd # or whatever
#string1a
#string2b
#string3c
#string4a
#string5b
#string6c
#string7a
#string8b
Note that while cycle will repeat its elements indefinitely, izip stops on the shortest iterable (list1).

list = [url1..1]
list2 = [a, b, c]
for i in list:
for a in list2:
v = i+a
EDIT
Okay, that makes more sense-
How about this...
set_it = iter(list2)
for i in list:
try:
a = set_it.next()
except:
set_it = iter(list2)
a = set_it.next()
v = i+a
Though I feel the same as you- there is probably a smoother way to accomplish that...

Related

How can I convert a list comprehension to a normal for loop?

I'm trying to learn how I can convert Python list comprehensions to a normal for-loop.
I have been trying to understand it from the pages on the net, however when I'm trying myself, I can't seem to get it to work.
What I am trying to convert is the following:
1:
n, m = [int(i) for i in inp_lst[0].split()]
and this one (which is a little bit harder):
2:
lst = [[int(x) for x in lst] for lst in nested[1:]]
However, I am having no luck with it.
What I have tried:
1:
n = []
for i in inp_lst[0].split():
n.append(int(i))
print(n)
If I can get some help, I will really appreciate it :D
Generally speaking, a list comprehension like:
a = [b(c) for c in d]
Can be written using a for loop as:
a = []
for c in d:
a.append(b(c))
Something like:
a, b = [c(d) for d in e]
Might be generalized to:
temp = []
for d in e:
temp.append(c(d))
a, b = temp
Something like:
lst = [[int(x) for x in lst] for lst in nested[1:]]
Is no different.
lst = []
for inner_lst in nested[1:]:
lst.append([int(x) for x in inner_lst])
If we expand that inner list comprehension:
lst = []
for inner_lst in nested[1:]:
temp = []
for x in inner_lst:
temp.append(int(x))
lst.append(temp)

How to pass the empty list when doing list comprehension

I have to create a list with all combination of three multiple lists:
a = ['1','2']
b = ['3','4']
c = ['5']
name = []
delimiter = '_'
name = [i + delimiter + j + delimiter + k for i in a for j in b if b for k in c]
print (name)
['1_3_5', '1_4_5', '2_3_5', '2_4_5']
My question is, on some occasions list c is empty.
c = []
print (name)
[]
Is there a way to prevent it returning as an empty list by altering the list comprehension, without removing "k in c"?
You can use an extendible method which does not rely on explicit nested for loops. For example, using itertools.product and filter:
from itertools import product
a = ['1','2']
b = ['3','4']
c = ['5']
res = ['_'.join(i) for i in product(*filter(None, (a, b, c)))]
# ['1_3_5', '1_4_5', '2_3_5', '2_4_5']
With empty c:
c = []
res = ['_'.join(i) for i in product(*filter(None, (a, b, c)))]
# ['1_3', '1_4', '2_3', '2_4']

how to assign index value of an array to the others array same index value in python

I have two lists naming A and B:
A = ["boy","girl","place","food"]
B = ["he","she","USA,UK","Pizza,Burger,Sushi"]
I want the output to be given as "he" when the user inputs "boy".In short I want the index value of elements in list A to be given the values of the same indices in the list B.
A[0] == B[0]
A[1] == B[1]
A[2] == B[2]
A[3] == B[3]
This is the exact thing I want.If I input the data given in A[i] , the output should be the given in the B[i].Thanks.
You can retrieve the index of the user input using .index(input_string) and then call B:
A = ["boy","girl","place","food"]
B = ["he","she","USA,UK","Pizza,Burger,Sushi"]
i = A.index('boy')
print B[i] # he
I think you need to consider dict combined out of those lists.
my_dict = dict(zip(A, B))
user_input = raw_in-put('enter a word\n')
if user_input in my_dict:
print my_dict[user_input]
First you must check that your input is indeed in A. Then, if it is, with the index method you find the index of the item in A, to access B with it.
A = ["boy","girl","place","food"]
B = ["he","she","USA,UK","Pizza,Burger,Sushi"]
input_string = 'place'
if input_string in A:
output_string = B[A.index(input_string)]
print(output_string) # outputs 'USA,UK'
I can with an extra dictionary you can may the values of A as keys to B values.
Look at the example below for more reference
A = ["boy","girl","place","food"]
B = ["he","she","USA,UK","Pizza,Burger,Sushi"]
dic = zip(A, B)
print(dic["boy"])
Hope this helps!
Ideally, you structure your data as a list of lists, because as it is now, it is very difficult to format a dictionary without knowing ahead of time which groups are needed:
A = ["boy","girl","place","food"]
B = ["he","she",["USA,UK"],["Pizza,Burger,Sushi"]]
new_data = {a:b for a, b in zip(A, B)}
print(new_data["boy"])
Output:
"he"
You definitely want a dict.
a_to_b = dict(zip(a,b))
print a_to_b['he'] == 'boy'
for key in a:
print key, a_to_b[key]
Use the builtin zip() function
A = ["boy","girl","place","food"]
B = ["he","she","USA,UK","Pizza,Burger,Sushi"]
for single_value_of_a, single_value_of_b in zip(A,B):
print(single_value_of_a, single_value_of_b)
Output:-
boy he
girl she
place USA,UK
food Pizza,Burger,Sushi

With 2 list of strings, trying to find a way to print the string in the same position/order from the opposite list.(Python)

Lets say I have list:
A = ['ldc','gnh','yjk','isd']
and
B = ['578','460','926','551']
My desired output would be:
gnh when my input is 460. (same position but from the other list) How to do this?
Make a dictionary where the keys would be the B list items and the values - A list items:
>>> d = dict(zip(B, A))
>>> d["460"]
'gnh'
Use the index built-in method to find the position in B.
Use that to grab the corresponding value from A.
Note that variable names do not go inside quotation marks.
A = ['ldc','gnh','yjk','isd']
B = ['578','460','926','551']
key = '460'
print A[B.index(key)]
for multiple entries:
for i, j in enumerate(B):
if j == key:
print A[i]
or a list thereof:
print [A[i] for i, j in enumerate(B) if j == key]
Output for the last one:
['gnh', '2nd']
you can use a generator and zip to scan and pair the lists
>>> key = '460'
>>> g = (a for a,b in zip(A,B) if b == key)
>>> next(g)
'gnh'
this also works for every occurrence of the key in the B list, in case it occurs more than once
e.g.
>>> A = ['ldc','gnh','yjk','isd']
>>> B = ['578','460','926','460']
>>> key = '460'
>>> g = (a for a,b in zip(A,B) if b == key)
>>> next(g)
'gnh'
>>> next(g)
'isd'
or use it as
>>> for el in g:
... print(el)
...
gnh
isd

How to loop over a circular list, while peeking ahead and behind current element?

With the following example list: L = ['a','b','c','d']
I'd like to achieve the following output:
>>> a d b
>>> b a c
>>> c b d
>>> d c a
Pseudo-code would be:
for e in L:
print(e, letter_before_e, letter_after_e
You could just loop over L and take the index i minus and plus 1 modulo len(L) to get the previous and next element.
You're pretty much there
for i, e in enumerate(L):
print(e, L[i-1], L[(i+1) % len(L)])
EDITED to add mod
it would probably be overkill in this case, but this is the general use-case for a circular doubly-linked list http://ada.rg16.asn-wien.ac.at/~python/how2think/english/chap17.htm
It's often simpler conceptually to keep track items you've already seen than to look ahead. The deque class is ideal for keeping track of n previous items because it lets you set a maximum length; appending new items automatically pushes old items off.
from collections import deque
l = ['a','b','c','d']
d = deque(l[-2:], maxlen=3)
for e in l:
d.append(e)
print d[1], d[0], d[2]
The only difference in this solution is that d c a will come first instead of last. If that matters, you can start out as though you've already seen one iteration:
from collections import deque
l = ['a','b','c','d']
d = deque(l[-1:] + l[:1], maxlen=3)
for e in l[1:] + l[:1]:
d.append(e)
print d[1], d[0], d[2]
In my code I would use a moving window of 3 elements over the list prepended by the last element and appended by the first element:
from itertools import tee, izip, chain
def window(iterable,n):
'''Moving window
window([1,2,3,4,5],3) -> (1,2,3), (2,3,4), (3,4,5)
'''
els = tee(iterable,n)
for i,el in enumerate(els):
for _ in range(i):
next(el, None)
return izip(*els)
def chunked(L):
it = chain(L[-1:], L, L[:1]) # (1,2,3,4,5) -> (5,1,2,3,4,5,1)
for a1,a2,a3 in window(it,3): # (3,1,2,3,1) -> (3,1,2), (1,2,3), (2,3,1)
yield (a2,a1,a3)
## Usage example ##
L = ['a','b','c','d']
for t in chunked(L):
print(' '.join(t))

Categories

Resources