【问题标题】:Is there a way to accept only the integer values after dividing a list? Answered有没有办法在划分列表后只接受整数值?已回答
【发布时间】:2020-09-23 14:35:05
【问题描述】:
# Creating List of integers
List = [112, 966, 483, 807, 112, 693, 507, 712, 738, 605, 923, 112, 966, 679, 992, 29, 782, 780, 353, 392]

print("\nList of numbers: ")

print(List)

# Create Divide variable
myInt = 13

#List values divided by 13
newList = [x / myInt for x in List]

print("\nList Divided by 13")

print (newList)

我现在正在尝试创建一个新列表,该列表仅是我列出的 newList 中除法的总和,但我只想保留整数,我将如何过滤掉它?

或者我想如果只是列出总共有多少个数字可以除以 myInt 然后将其输出为整数,那会更容易吗?

【问题讨论】:

  • 看看这个post。它解释了如何仅获取数组的整数值(在除法之后),然后为了得到结果,您只需找到该过滤数组的长度。
  • 请完成关于模运算符的简短教程,%

标签: python list numbers integer output


【解决方案1】:

您可以使用模运算符。 someNum % yourInt 如果它是可整除的,则不会给出余数,因此它将返回 0。您可以使用它来过滤。

if a % myInt == 0:
    # add to list 

你可以在这里找到更多信息:https://www.geeksforgeeks.org/what-is-a-modulo-operator-in-python/(或者只是搜索模运算符)

【讨论】:

    【解决方案2】:

    您需要在列表中使用if 检查您的newList

    newList = [int(x / myInt) for x in List if x/myInt % 1 == 0 ]
    

    结果将是[39, 71, 60]

    或者您希望每个数字都可以使用整数部分

    newList = [x // myInt for x in List ]
    

    看看This post

    【讨论】:

    • 谢谢,但试图理解最后一部分,即您要输入的 if 语句,是 %1 ==0 使任何不显示小数的东西吗?
    • 小数不显示,因为int(x / myInt) 删除了小数部分。这行含义就像`将myList中的每个项目按顺序获取为x,如果x mod myInt等于0,则将其转换为int然后将其放入response(newList)`如果一个值有小数部分,它将被过滤掉,因为%1 不是 0`
    • 非常感谢您的解释!想知道为什么会这样,我还没有接触到模数运算,所以我不理解其他一些帖子/答案
    猜你喜欢
    • 2021-07-24
    • 2020-01-24
    • 2020-05-10
    • 1970-01-01
    • 2023-02-08
    • 2022-11-02
    相关资源
    最近更新 更多