简体   繁体   English

Python 3.6 如何检查一个列表是否包含一个带字母的字符串并且还包含一个整数?

[英]Python 3.6 how to check to see if a list contains a string with letters and also contains an integer?

How can I check to see if a list contains a string that itself does not contain any digits?如何检查列表是否包含本身不包含任何数字的字符串? The list in question will have a string with letters or digits and an integer.有问题的列表将包含一个包含字母或数字的字符串和一个整数。

You can use a combination of a list comprehension to iterate over the input_list , any() to return True the second you encounter the first string with an int() (early exits are always a good idea), and a regex to see if a digit or letter is in the string ( [0-9] matches any single digit and [a-zA-Z] any letter in a string; re.search() will evaluate True if either of thesestrings match).您可以使用列表input_list的组合来迭代input_listany()在遇到第一个字符串时返回Trueint() (提前退出总是一个好主意),并使用正则表达式来查看是否数字或字母在字符串中( [0-9]匹配任何单个数字, [a-zA-Z]匹配字符串中的任何字母;如果这些字符串中的任何一个匹配, re.search()将评估为True )。

Based on the question, you want to check if any string inside the list contains at least one letter and at least one number, but if it has only numbers or letters it is fine.基于这个问题,您想检查列表中的任何字符串是否包含至少一个字母和至少一个数字,但如果它只有数字或字母,那就没问题了。 I'm not exactly sure which condition you wish to check for ;我不确定您希望检查哪种情况; If my interpretation is off, I am happy to edit the code below to match your intent.如果我的解释不正确,我很乐意编辑下面的代码以符合您的意图。

import re
input_list = [11, "11", "somestring", "someotherstring", "mixedstring1"]
any([x for x in input_list if re.search("[0-9]", str(x)) and re.search("[a-zA-Z]", str(x))])

True

Your Q is unclear, but I think that for this list:您的 Q 不清楚,但我认为对于此列表:

l = ['bob', 'fish', 'abc123']

you want to False as the list does contain a string with digits.你想要False因为列表确实包含一个带数字的字符串。

And for the following:对于以下情况:

l = ['bob', 'fish', 'abc']

you want True as there are no strings with digits.你想要True因为没有带数字的字符串。

To achieve both of these results, you can use:要实现这两个结果,您可以使用:

not any(any(c.isdigit() for c  in s) for s in l)

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

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