簡體   English   中英

理解期間列表中的python類型

[英]python types in list during comprehension

我有一個如下的sql查詢字符串:

intro text,
id int,
description varchar(50)

我正在嘗試創建一個類型字符串,目的是查找與sql模式中定義的類型不匹配的文本。 我從sql文本中提取類型的方式如下:

types = [re.sub('[^a-zA-Z]','',x.split()[1]) for x in schema] 
types = [re.sub('varchar',types.StringType,x) for x in types]
types = [re.sub('text',types.StringType,x) for x in types]
types = [re.sub('bigint',types.IntType,x) for x in types]
types = [re.sub('decimal',types.IntType,x) for x in types]

但是口譯員抱怨說

types = [re.sub('varchar',types.StringTypes,x) for x in types]
AttributeError: 'list' object has no attribute 'StringTypes'

SSCCE

使用以下架構文件

intro text,
id int,
description varchar(50)

和代碼(注意,如下面的奧斯卡建議的那樣已修復,但現在有其他錯誤)

import csv
import sys
import re
import types

sch = open(sys.argv[1], "rb")

#---------------------------------   
# read schema
#---------------------------------     
with sch as f:
    schema = f.read().splitlines()

#---------------------------------    
# extract schema types
#---------------------------------  

foundtypes = [re.sub('[^a-zA-Z]','',x.split()[1]) for x in schema] 
foundtypes = [re.sub('varchar',str,x) for x in foundtypes]
foundtypes = [re.sub('text',str,x) for x in foundtypes]
foundtypes = [re.sub('int',int,x) for x in foundtypes]
foundtypes = [re.sub('bigint',int,x) for x in foundtypes]
foundtypes = [re.sub('decimal',int,x) for x in foundtypes]

print foundtypes

我正在使用Python 2.7.5

謝謝

在這一行中,您將綁定重寫(參見: variable shadowing )到types 模塊

types = [re.sub('[^a-zA-Z]','',x.split()[1]) for x in schema]

之后, types不再指向模塊,而是指向列表。 只需在所有作業中使用另一個名稱即可:

my_types = [re.sub('[^a-zA-Z]','',x.split()[1]) for x in schema] 
my_types = [re.sub('varchar',types.StringType,x) for x in my_types]
my_types = [re.sub('text',types.StringType,x) for x in my_types]
my_types = [re.sub('bigint',types.IntType,x) for x in my_types]
my_types = [re.sub('decimal',types.IntType,x) for x in my_types]

更新

我認為您對解決方案進行了過度設計,除了第一行以外,這不適合使用正則表達式。 一個簡單的if-elif-else可以正常工作:

def transform(typestr):
    if typestr in ('varchar', 'text'):
        return types.StringType
    elif typestr in ('int', 'bigint', 'decimal'):
        return types.IntType
    else:
        return None

my_types = [re.sub(r'[^a-zA-Z]', '', x.split()[1]) for x in schema] 
[transform(x) for x in my_types]
=> [<type 'str'>, <type 'int'>, <type 'str'>]

您正在覆蓋模塊types模塊。 更改要保存到的列表的名稱,它應該可以使用。

foundtypes = [re.sub('[^a-zA-Z]','',x.split()[1]) for x in schema] 
foundtypes = [re.sub('varchar',types.StringType,x) for x in foundtypes]
foundtypes = [re.sub('text',types.StringType,x) for x in foundtypes]
foundtypes = [re.sub('bigint',types.IntType,x) for x in foundtypes]
foundtypes = [re.sub('decimal',types.IntType,x) for x in foundtypes]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM