【问题标题】:How to produce a list of odd indices from a number in Python?如何从 Python 中的数字生成奇数索引列表?
【发布时间】:2021-03-27 13:06:52
【问题描述】:

我想生成一个仅包含 Python 整数的奇数索引的列表。

这是我尝试做的:

number = 5167460267890853
numberList = [num for num in str(number)]
oddIndex = [num for num in numberList if numberList.index(num) % 2 == 0]
print(oddIndex)

输出:

['5', '6', '4', '6', '0', '6', '8', '0', '8', '5']

预期输出:

['5', '6', '4', '0', '6', '8', '0', '5'] 

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    您可以使用步长为2 的字符串切片。 将数字转换为字符串,只取奇数索引,然后转换为列表。

    在您的尝试中使用这种方法,您可以尝试:

    number = 5167460267890853
    numberList = [num for num in str(number)]
    numberList = numberList[::2]
    

    或者只使用list 内置函数:

    number = 5167460267890853
    oddIndex = list(str(number)[::2])
    

    两者都产生所需的输出。

    类似问题的答案也使用类似的技术here

    【讨论】:

      【解决方案2】:

      list.index() 将返回列表中第一个看到的元素的索引。你可以使用enumerate() 代替这个例子:

      number = 5167460267890853
      out = [num for k, num in enumerate(str(number)) if not (k % 2)]
      print(out)
      # ['5', '6', '4', '0', '6', '8', '0', '5']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-04
        • 2019-06-30
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 1970-01-01
        • 2021-05-14
        相关资源
        最近更新 更多