【问题标题】:Create A Function To Find Elements Of Same Length In Tuple/List创建一个函数以在元组/列表中查找相同长度的元素
【发布时间】:2021-10-21 17:52:18
【问题描述】:

我正在尝试创建一个以整数作为参数的函数,并使用它来显示元组/列表中具有相同长度的元素

names=('Delta', 'Omega', 'Alpha', 'Charlie', 'Beta')
num_letter = Input('enter number')


def number_letters_same_length(int(num_letter))
if len(names) == int(num_letter):
    print(names)
else:
print('no names with same length found')

目标是显示在参数中输入的具有相同编号的所有名称的列表,如果不是,则应显示错误消息“未找到具有相同长度的名称”

【问题讨论】:

  • 您需要遍历名称列表并将每个名称 len 与所需的 len 进行比较
  • 输入不是内置函数

标签: python string list function tuples


【解决方案1】:

这个呢

name_list = [name for name in names if len(name) == num_letter]
if name_list:
   print(name_list)
else:
   print('no names with same length found')

【讨论】:

    猜你喜欢
    • 2020-05-08
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2020-08-03
    相关资源
    最近更新 更多