首先,您可能会更好地为变量命名。而不是G
和F
,letter
和strings
怎么样?你的代码是这样的:
def match_first_letter(letter, strings):
for current_string in strings:
if current_string.strings[0] == letter:
return strings
在这种情况下,你已经看到的错误反而说AttributeError: 'str' object has no attribute 'strings'
。请注意,这与current_string.strings
命令相匹配。
current_string[0]
是你真正想要的东西对匹配letter
进行测试,因为这是字符串current_string
的第一个字母。
最后,您目前正在返回列表。相反,您应该将current_string
添加到要返回的列表中。
def match_first_letter(letter, strings):
matched_strings = []
for current_string in strings:
if current_string[0] == letter:
matched_strings.append(current_string)
return matched_strings
的Python实际上有一种叫做list comprehensions它可以更容易地做这种事情。
def match_first_letter(letter, strings):
return [string_x for string_x in strings if string_x[0] == letter]
我推荐阅读上面链接的列表推导。
? –
您的错误与您的代码不符。 – vaultah
我期望i.F [0]遍历列表中的每个项目并返回满足参数 – SystemofaCode