谁能详细解释一下这是什么意思?f for f in...例如
list = [f for f in os.listdir(os.getcwd()) if os.path.isdir(f)]
print(list)
Run Code Online (Sandbox Code Playgroud)
我了解基本 for 循环的语法,但我已经多次看到这种类型的事情,并且发现它非常令人困惑。我一直在搜索,我所能找到的只是有关格式化的信息。我大约一个月前才开始学习Python,并且仍在学习中。感谢您的任何帮助!
我知道这是一个简单的问题,但我有一个包含数百个字符串的列表,我需要帮助尝试选择其中的几个。例如,列表是:
lines = ["First Sentence dog", "Second Sentence dog", "Third Sentence cat", "Fourth Sentence cat"...]
Run Code Online (Sandbox Code Playgroud)
我需要访问和操作包含单词“dog”的索引。我到目前为止的代码是:
for line in range(len(lines)):
if "dog" in line:
# Do some something
elif "cat" in line:
# Do some something else
else:
# Do other things
Run Code Online (Sandbox Code Playgroud)
感谢您的任何帮助!
编辑:我得到的错误是 TypeError: argument of type 'int' is not iterable
具体来说,我的问题是:如何通过搜索其中的特定子字符串来检索整个字符串并对其进行处理?