Skip to content Skip to sidebar Skip to footer

Assign Differing Values To List Generator Results

I am using list generators as shown below. I would like to know how I can assign different text or values to the individual list generators. In the sample code, I can only assign v

Solution 1:

There are a couple of different ways of assigning additional values to the different generators. The easiest would be to have a dictionary keyed by the generator or an iterable of the same length containing the values. Both approaches are shown here:

Iterable

v = (item for item in propadd if item[0]==row1[8] and harversine(custx,custy,item[2],item[3])<1500)
k = (item for item in custadd if item[0]==row1[4])
m = (item for item in numlist if re.search(r"^[0-9]+(?=\s)",row1[0]) isnotNoneand item[0]==re.search(r"^[0-9]+(?=\s)",row1[0]).group())
extraValues = ('value 1', 'value 2', 'value3')
for ind, gen inenumerate((v, k, m)):
    l = list(gen) 
    iflen(l) == 1:
        row1[1] = l[0][1]
        row1[2] = l[0][2]
        row1[3] = extraValues[ind]
        break

Dictionary

v = (item for item in propadd if item[0]==row1[8] and harversine(custx,custy,item[2],item[3])<1500)
k = (item for item in custadd if item[0]==row1[4])
m = (item for item in numlist if re.search(r"^[0-9]+(?=\s)",row1[0]) isnotNoneand item[0]==re.search(r"^[0-9]+(?=\s)",row1[0]).group())
extraValues = {v: 'value 1',
               k: 'value 2',
               m: 'value3')
for gen in (v, k, m):
    l = list(gen) 
    iflen(l) == 1:
        row1[1] = l[0][1]
        row1[2] = l[0][2]
        row1[3] = extraValues[gen]
        break

You could also have some complex scenario where the extra value could be generated by some function other than a dictionary lookup or tuple index.

Post a Comment for "Assign Differing Values To List Generator Results"