如何将列表列表转换为int?

2024-09-28 01:28:00 发布

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

我不理解Python中的一个基本概念(C guy),可以使用a)答案b)解释

def do_the_deed(srctxt, upperlower)
# srctxt = "XGID=-b----E-C---eE---c-e----B-:0:0:1:21:0:0:1:0:10"

    alpha_list = srctxt[5:31]

    # map chars to ascii
    # [45],[66],[45],[45]....
    ord_list = [map(ord, x) for x in alpha_list]

    count = 0
    # what I want to do but can not!!!
    ??? for y = int(x) in ord_list  ???
        if y <> 45                    # acs('-') == 45
            if upperlower = 'UPPER'
                if ((y>= 97) and (y<= 112)):  # uppercase 15 valid
                    count += y - 96
            if upperlower = 'LOWER'
                if ((y>=65) and (y<=80)):     # lower case 15 valid
                    count += y - 64
     return count

我想有一个整洁的方法让我做到这一点

xval = [int(x) for x in ord_list[0]]

给我第一个值。你知道吗

我可以显式地迭代从0到26的范围,但这似乎是错误的想法。我一直在谷歌搜索,但我不知道合适的搜索条件。迭代器,枚举,强制转换。。。C型术语不能给我正确的答案。你知道吗

谢谢你, 罗伯特


Tags: andto答案inalphamapforif
2条回答

你的问题来自这一行:

ord_list = [map(ord, x) for x in alpha_list]

您将创建两个列表,一个使用列表理解([ ... for x in ...]),另一个使用map。因此,当(我假设)您只需要整数列表时,您将以字符代码列表结束:

  • 目前您有:ord_list[[45], [98], [45], ..., [66], [45]]
  • 你需要的是:ord_list[45, 98, 45, ..., 66, 45]

您可以通过map(ord, alpha_list)[ord(x) for x in alpha_list]获得它

所以你的代码可以是:

...
alpha_list = srctxt[5:31]

# map chars to ascii
# [45],[66],[45],[45]....
ord_list = map(ord, alpha_list)  # or [ord(x) for x in alpha_list]

count = 0
# what I want to do but can not!!! now you can :-)
for y in ord_list:
    if y <> 45:
        ...

在Python中,经常需要使用字典:

import string
def do_the_deed(srctxt, upperlower):
    chars = string.lowercase if upperlower == 'LOWER' else string.uppercase
    translate = dict(zip(chars, range(1,27)))
    return sum(translate.get(c, 0) for c in srctxt[5:31])

相关问题 更多 >

    热门问题