Assign differing values to list generator results

社会主义新天地 提交于 2020-01-05 22: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:


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.



来源:https://stackoverflow.com/questions/33578676/assign-differing-values-to-list-generator-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!