Python:将变量置于循环之外

时间:2016-12-20 14:22:46

标签: python-3.x

我有以下代码:

with replaced_string as (
    select 'a,a,a,b,c,b,d,a,d' as str   from dual union all
    select 'a,a,a,b,c,d,a,d,d' as str   from dual
)
,expr_for_replace as (
    select 'a,b,a,d' as pattern from dual
)
,recursive_call (str, lvl, parent_str) as (
    select t.str as str, 1 as lvl, t.str as parent_str
    from replaced_string t
    union all
    select case
             when regexp_instr(r.str, v.val, 1, 2) > 0
             then regexp_replace(r.str,v.val,null,1,1)
             else r.str
           end str
          ,r.lvl + 1 as lvl
          ,r.parent_str as parent_str
    from recursive_call r
    left join (select regexp_substr(pattern, '[^,]+',1,level) as val
                     ,level as lvl
               from expr_for_replace
               connect by regexp_substr(pattern, '[^,]+',1,level) is not null) v on (v.lvl = r.lvl)
    where v.lvl is not null
)

select parent_str as string_before
      ,str        as result_string
from (select c.*
            ,row_number() over(partition by parent_str order by c.lvl desc) as rn
      from recursive_call c)
where rn = 1

我更新了这个问题。 以下是输出:

for response_i in response['response']:

  var_1=None
  if response_i['objkey'] == 'explorecube_data':
      var_1=response_i['objcontent'][0]['title']
  if response_i['objkey'] == 'explorecube_data' and response_i['objcontent'][0]['title'] == var_1:
    print(var_1)

  dim_1=None
  if response_i['objkey'] == 'explorecube_dimvalues':
      dim_1=response_i['objcontent'][0]['title']
  if response_i['objkey'] == 'explorecube_dimvalues' and response_i['objcontent'][0]['title'] == dim_1:
      print(dim_1)

  ab=[var_1, dim_1]
  print(ab)

我想得到以下输出:

['tos', None]
[None, None]
[None, 'lat']
[None, None]

我感谢任何解决此问题的建议

3 个答案:

答案 0 :(得分:2)

使用生成器生成所需的结果,然后将其打印出来。

def PrintGen():
    for response_i in response['response']:
        if response_i['objkey'] == 'explorecube_data' or response_i['objkey'] == 'explorecube_dimvalues':
            yield response_i['objcontent'][0]['title']
ab =PrintGen()
listab =list(ab)
print(listab)

生成器用于生成满足需求的对象,它们适合您。

答案 1 :(得分:0)

尝试这样的事情,应该将数据转换为pandas数据帧并删除None值

import pandas as pd


data = []

data.append([var_1, dim_1])

df = pd.DataFrame(data, columns=['var_1', 'dim_1'])
df = df.dropna(how = 'all')

答案 2 :(得分:0)

当值不是ab时,您只需将值附加到None。然后您需要在循环之外实例化并打印ab

ab = []
for response_i in response['response']:
  var_1=None
  if response_i['objkey'] == 'explorecube_data':
      var_1=response_i['objcontent'][0]['title']
  if response_i['objkey'] == 'explorecube_data' and response_i['objcontent'][0]['title'] == var_1:
    print(var_1)
    ab.append(var1)

  dim_1=None
  if response_i['objkey'] == 'explorecube_dimvalues':
      dim_1=response_i['objcontent'][0]['title']
  if response_i['objkey'] == 'explorecube_dimvalues' and response_i['objcontent'][0]['title'] == dim_1:
      print(dim_1)
      ab.append(dim1)

print(ab)