【问题标题】:Select elements of list based on number of characters [duplicate]根据字符数选择列表元素[重复]
【发布时间】:2021-01-19 22:04:18
【问题描述】:

打印数组长度大于等于4的元素,如

things = ['jump','hop','skip','tip',leap']

【问题讨论】:

  • 遍历列表(例如使用for value in things:)并调用len()
  • [e for e in things if len(e)>=4]

标签: python arrays math integer boolean


【解决方案1】:

您可以检查元素长度是否大于四,然后您可以将它们添加到所需的列表中

new_elements =[element for element in things if len(element)>=4]
print(new_elements)

【讨论】:

    【解决方案2】:

    我建议你自己想出答案。 一些提示是:

    1. 使用“for”循环遍历列表中的每个元素LINK 示例:
    fruits = ["apple", "banana", "cherry"]
    
    for x in fruits:
     print(x)
    
    1. 在循环中,使用 len() 检查列表中每个元素的长度。 示例:
     if len(element1) >=4: 
        do something
    

    完整代码如下

    fruits = ["apple", "banana", "cherry"]
    
    for x in fruits:
     if len(x) >=4: 
       print(x)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      相关资源
      最近更新 更多