【问题标题】:How do I make certain list items lowercase using str.lower() if they appear on another list?如果某些列表项出现在另一个列表中,如何使用 str.lower() 将它们设为小写?
【发布时间】:2020-12-12 20:24:34
【问题描述】:

我一直在尝试解决 CodeWars 上的一个问题,但遇到了障碍。我知道这不是一种特别“pythonic”的方法(我是初学者)。而且我确信有更有效和更先进的方法可以做到这一点。但我真的只是想了解为什么下面的代码不起作用。如果它们出现在另一个过滤词列表中,我只想将列表的字符串项设为小写。 (忽略删除第一项的代码。那是因为该任务需要以不同的方式处理第一项)。

def title_case(title, minors=''):
    title = title.title()
    mwds = minors.split()
    lst = title.split(" ", 1)

    exfirst = lst[1].split()
    for wd in exfirst:
        wd.lower()
        if wd in mwds:
            wd.lower()
    return exfirst

print(title_case('a clash of KINGS', 'a an the of'))
print(title_case('THE WIND IN THE WILLOWS', 'The In'))

结果:

['Clash', 'Of', 'Kings']
['Wind', 'In', 'The', 'Willows']

预期结果:

['Clash', 'of', 'Kings']
['Wind', 'in', 'the', 'Willows']

【问题讨论】:

  • 您的代码格式错误,请修正缩进。 str.lower() 返回字符串的小写副本,它不会改变原始字符串。字符串是不可变的。

标签: python list filter lowercase


【解决方案1】:

这是因为您没有将新的未成年人分配给旧的未成年人。要进行分配,您必须在 exfirst 列表中使用索引作为迭代器。

for i in range(exfirst):
    wd= exfirst[i].lower()
    if wd in mwds:
        exfirst[i] = wd

【讨论】:

    【解决方案2】:

    lower() 方法不会就地更改字符。你应该这样做:

    wd = wd.lower()
    

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多