python-3.x - Python - 如何输出列表中包含一定数量字母的字符串
问题描述
使用 Python 3.7,我有一个包含各种长度的字符串的列表。我正在尝试使用函数只返回有两个字母的字符串——我的阈值。当我真的想要打印“a”、“ab”和“ac”时,我目前得到了“a”的单个字符串输出。我不知道我哪里出错了?我知道 len(xStr) 会计算字符串中的字母数,但我不确定如何在这里正确使用它。
这是我尝试的代码:
threshold = 2
def listOfWords(list):
stringList = ["a", "ab", "abc", "ac", "abcd"]
return stringList
def wordsInListsCounter():
for elements in listOfWords(list):
if len(elements) <= threshold:
strLessThanThreshold = elements
return strLessThanThreshold
elif len(elements) == 0:
emptyString = "There are no words in this list"
return emptyString
else:
error = "There is invalid information"
return error
print(wordsInListsCounter())
任何帮助,将不胜感激!!我是这里的新手 Python 用户...
解决方案
使用列表推导:
>>> stringList = ["a", "ab", "abc", "ac", "abcd"]
>>> modifiedList = [x for x in stringList if len(x) <= 2]
>>> modifiedList
['a', 'ab', 'ac']
我已经编辑了我的答案以更好地匹配您的问题,这是我要添加的内容:
threshold = 2
myList = ["a", "ab", "abc", "ac", "abcd"]
def wordsInListsCounter(stringList):
elements = []
for element in stringList:
if len(element) <= threshold:
elements.append(element)
return elements
elements = wordsInListsCounter(myList)
if len(elements) == 0:
print("There are no words in this list")
else:
print(elements)
推荐阅读
- python - Pyhon Django有什么问题?/ 'NoneType' 对象没有属性 'page_range'
- powershell - 每天备份 QVD 文件并在删除第一代之前保存三个版本
- gitlab - gitlab-runner 缓存文件大小每次都增加一倍
- python - 如何迭代字典中的值?
- arrays - 如何在 MATLAB 中使用元胞数组制作稀疏矩阵?
- python - 如何循环 NetCDF 时间序列
- java - (Box2dLights) 禁用某个纹理的光?
- php - 即使电子邮件已经存在,条件也不起作用并提交表单
- java - IllegalStateException No view found forFragment 在活动中替换片段时
- c# - 使用读/写检查连接到 NAS 服务器。模拟失败