问题描述
我正在使用列表生成器,如下所示.我想知道如何为各个列表生成器分配不同的文本或值.在示例代码中,我只能一次为所有列表生成器分配值.例如,我想为v
,row1[3]="value 1"
,k
,row1[3]="value 2"
和m
,row1[3]="value 3".
指定如何实现?
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
推荐答案
有两种不同的方法可以将附加值分配给不同的生成器.最简单的方法是由生成器键入一个字典或包含值的相同长度的可迭代字典.两种方法都显示在这里:
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:
可迭代
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
词典
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.
这篇关于分配不同的值以列出生成器结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!