You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字符串匹配首字母大写阶段列表推导式结果无法打印问题

问题修复方案

核心问题说明

你的代码运行后输出方法对象列表、匹配逻辑失效的核心原因有三点:

  • 循环缩进错误,首字母提取、匹配逻辑完全脱离了遍历候选标题的外层循环,仅会处理最后一个候选标题
  • 调用字符串title方法时遗漏了括号,你拿到的是方法本身的对象引用,而非首字母大写后的字符串结果
  • 首字母列表追加时机错误,在内层遍历单个标题单词的循环中反复追加不完整的首字母列表,会导致匹配逻辑完全混乱

修正后可运行代码

titres = []
acro = input().lower()
acro = list(acro)
nb_Livres = int(input())

temp =[]
l4 = []


def main():
    for i in range(nb_Livres):
        titre = input().lower().split()
        titres.append(titre)
        if len(titre) == len(acro):
            temp.append(titre)

    # 修正缩进,将首字母提取、匹配逻辑纳入外层遍历候选标题的循环内
    for i in range(len(temp)):
        titre = temp[i]
        prem_lettre = [0] * len(titre)
        for j in range(len(titre)):
            prem_lettre[j] = titre[j][0]
        # 完整提取完当前标题所有首字母后再比对、存储
        if acro == prem_lettre:
            l4.append(titre)
    
    # 修正title方法调用,添加括号执行方法
    x = [[sub_element.title() for sub_element in element] for element in l4]
    # 该步转换可省略,title()执行后返回的本身就是字符串,如无额外需求可直接打印x
    y = [[str(sub_item) for sub_item in items] for items in x]

    print(y)

main()

补充说明

如果需要输出拼接好的完整标题字符串而非嵌套列表,可以将打印逻辑替换为:

for item in y:
    print(' '.join(item))

内容的提问来源于stack exchange,提问作者de Beyssac Olivier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:45:03