理解期间列表中的python类型

2024-09-30 04:33:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个sql查询字符串,如下所示:

intro text,
id int,
description varchar(50)

我试图创建一个类型字符串,目标是查找与sql模式中定义的类型不匹配的文本片段。我从sql文本中提取类型的方法如下:

^{pr2}$

但是翻译抱怨说

^{3}$

一个SSCCE

使用以下架构文件

intro text,
id int,
description varchar(50)

和代码(请注意,按照下面oscar的建议进行了修复,但现在出现了其他错误)

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

我使用的是python2.7.5

谢谢你


Tags: 字符串textinimportreid类型for
2条回答

您将绑定(请参见:variable shadowing)覆盖到typesmodule,如下所示:

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

之后,types不再指向模块,而是指向一个列表。在所有作业中使用另一个名称:

^{pr2}$

更新

我认为你设计了太多的解决方案,除了第一行,这不适合使用正则表达式。一个简单的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]

相关问题 更多 >

    热门问题