Assign differing values to list generator results

2019-08-12 17:52发布

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 values for all the list generators at once. For example, I would like to assign for v, row1[3]="value 1", for k,row1[3]="value 2" and for m, row1[3]="value 3". How can I acheive that?

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]) is not None and item[0]==re.search(r"^[0-9]+(?=\s)",row1[0]).group())
for gen in (v, k, m):
    l = list(gen) 
    if len(l) == 1:
        row1[1] = l[0][1]
        row1[2] = l[0][2]
        break

1条回答
Evening l夕情丶
2楼-- · 2019-08-12 18:10

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]) is not None and item[0]==re.search(r"^[0-9]+(?=\s)",row1[0]).group())
extraValues = ('value 1', 'value 2', 'value3')
for ind, gen in enumerate((v, k, m)):
    l = list(gen) 
    if len(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]) is not None and 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) 
    if len(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.

查看更多
登录 后发表回答