【问题标题】:How can I find out if a list contains letters without using any libraries?如何在不使用任何库的情况下找出列表是否包含字母?
【发布时间】:2022-01-16 08:31:22
【问题描述】:

在列表列表中:

list=[['3','4','5'],['6','3','5'],['hello','goodbye','something56']]

我想去掉那个有字母的。我的尝试是:

for i in sub_list:
    if '.*[a-z]+.*' in i:
        continue
    else:
        print(i)

但是,这不起作用。

【问题讨论】:

  • in 不执行正则表达式匹配,顺便说一句
  • 不要使用list(或任何其他built-in function的名称)作为变量名。这会遮蔽内置,阻止您以后使用它。它还使您的代码更难阅读。

标签: python list loops


【解决方案1】:

尝试使用 str.isalpha() 来检查字符串是否包含字母

list_of_lists = [['3','4','5'], ['6','3','5'], ['hello','goodbye','something56']]
for sub_list in list_of_lists:
    if any(x.isalpha() for x in sub_list):
        continue    #this is what you are looking for
    else:
        print(sub_list)

输出

['3', '4', '5']
['6', '3', '5']

【讨论】:

    【解决方案2】:
    • 仅使用基本 Python(无库)
    • 命名变量列表的形式很糟糕,因为它隐藏了内置函数列表。

    代码

    numbers = "0123456789"  # list of digits
    lst = [['3','4','5'],['6','3','5'],['hello','goodbye','something56'], ['2', '4', 'today']]
    
    new_lst = []
    for sublist in lst:
        new_sublist = []
        for item in sublist:
            for c in item:
                if not c in numbers:
                    break
            else:
              # no break encountered so only numbers in for c in item
              continue
            break   # break in for c initem, so issue break in for item in sublist
        else:
          # no break, so all items where numbers
          new_lst.append(sublist)  # sublist only had numbers
            
    print(new_lst)
    # Output: [['3', '4', '5'], ['6', '3', '5']]
    

    【讨论】:

      猜你喜欢
      • 2014-08-02
      • 2012-02-22
      • 1970-01-01
      • 2011-07-04
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多