【问题标题】:How to cast a list of lists into ints?如何将列表列表转换为整数?
【发布时间】:2015-11-28 18:50:57
【问题描述】:

我不了解 Python(C 人)中的基本概念,可以使用 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 的范围,但这似乎是错误的想法。我一直在谷歌搜索,但我不知道要搜索的正确术语。 Iterator、Enumerate、Cast...C 类型的术语没有让我得到正确的答案。

谢谢, 罗伯特

【问题讨论】:

  • 试试for y in [x[0] for x in ord_list]
  • 我不确定您在这里要做什么,或者您的要求究竟是什么。您的第一个列表理解已经很奇怪,因为它转换为单值整数列表的列表。你为什么要这样做呢?为什么不干脆做ord_list = [ord(x) for x in alpha_list],然后就可以直接遍历ord_list了?
  • 你是指一个值xval = int(ord_list[0])还是列出xval =[int(x) for x in ord_list](没有[0]
  • 不要使用&lt;&gt; 进行比较,它很神秘且已弃用。请改用!=
  • ord_list 是整数列表,因此您不需要使用int()

标签: python list foreach casting integer


【解决方案1】:

您的问题来自这一行:

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:
        ...

【讨论】:

    【解决方案2】:

    在 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])
    

    【讨论】:

      猜你喜欢
      • 2016-12-16
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多