Python Slice How-to,我知道Python Slice,但我怎么才能使用内置的Slice对象呢? [英] Python slice how-to, I know the Python slice but how can I use built-in slice object for it?

查看:24
本文介绍了Python Slice How-to,我知道Python Slice,但我怎么才能使用内置的Slice对象呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内置函数slice有什么用处,如何使用?
我知道的Python切片的直接方法-l1[start:stop:step]。我想知道我是否有切片对象,那么如何使用它?

推荐答案

通过调用Slice来创建切片,其字段与执行[START:END:STEP]表示法时使用的字段相同:

sl = slice(0,4)

要使用切片,只需将其作为索引传递到列表或字符串即可:

>>> s = "ABCDEFGHIJKL"
>>> sl = slice(0,4)
>>> print(s[sl])
'ABCD'

假设您有一个固定长度的文本字段文件。您可以定义切片列表,以便轻松地从此文件中的每个";记录";中提取值。

data = """
0010GEORGE JETSON    12345 SPACESHIP ST   HOUSTON       TX
0020WILE E COYOTE    312 ACME BLVD        TUCSON        AZ
0030FRED FLINTSTONE  246 GRANITE LANE     BEDROCK       CA
0040JONNY QUEST      31416 SCIENCE AVE    PALO ALTO     CA""".splitlines()


fieldslices = [slice(*fielddef) for fielddef in [
    (0,4), (4, 21), (21,42), (42,56), (56,58),
    ]]
fields = "id name address city state".split()

for rec in data:
    for field,sl in zip(fields, fieldslices):
        print("{} : {}".format(field, rec[sl]))
    print('')

# or this same code using itemgetter, to make a function that
# extracts all slices from a string into a tuple of values
import operator
rec_reader = operator.itemgetter(*fieldslices)
for rec in data:
    for field, field_value in zip(fields, rec_reader(rec)):
        print("{} : {}".format(field, field_value))
    print('')

打印:

id : 0010
name : GEORGE JETSON    
address : 12345 SPACESHIP ST   
city : HOUSTON       
state : TX

id : 0020
name : WILE E COYOTE    
address : 312 ACME BLVD        
city : TUCSON        
state : AZ

id : 0030
name : FRED FLINTSTONE  
address : 246 GRANITE LANE     
city : BEDROCK       
state : CA

id : 0040
name : JONNY QUEST      
address : 31416 SCIENCE AVE    
city : PALO ALTO     
state : CA

这篇关于Python Slice How-to,我知道Python Slice,但我怎么才能使用内置的Slice对象呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆