繁体   English   中英

如何在不使用任何库的情况下找出列表是否包含字母?

[英]How can I find out if a list contains letters without using any libraries?

在列表列表中:

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

我想摆脱那个有字母的人。 我的尝试是:

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

但是,这是行不通的。

尝试使用 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)

Output

['3', '4', '5']
['6', '3', '5']
  • 仅使用基本的 Python(无库)
  • 命名变量列表的形式很糟糕,因为它隐藏了内置的 function 列表。

代码

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']]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM