【问题标题】:Change case to lower [closed]改变案例以降低[关闭]
【发布时间】:2019-05-21 21:23:33
【问题描述】:

我是 python 新手,正在尝试将许多字符串的大小写更改为小写。

许多字符串作为列表的元素包含,列表本身是字典的键(字符串数据类型)的值。

这是字典:

{
'1000268201_693b08cb0e'  :  ['A child in a pink dress is climbing up a set  of stairs in an entry way .', 'A girl going into a wooden building .', 'A little girl climbing into a wooden playhouse .', 'A little girl climbing the stairs to her playhouse .', 'A little girl in a pink dress going into a wooden cabin .'],
'101654506_8eb26cfb60'   :  ['A brown and white dog is running through the snow .', 'A dog is running in the snow', 'A dog running through snow .', 'a white and brown dog is running through a snow covered field .', 'The white and brown dog is running over the surface of the snow .']
}

我为上述字典编写的代码,键为1000268201_693b08cb0e101654506_8eb26cfb60,作为句子列表的值是:

for i in mapping:
    for j in range(0,len(mapping[i])):
        mapping[i][j]=mapping[i][j].lower();

什么是完成上述工作的有效而简洁的方法?

【问题讨论】:

  • 它适用于我:ideone.com/g1m5A2
  • @Drako 真的?????
  • @Drako 这在很多层面上听起来都是错误的,其中最重要的是97-65 != 22
  • 是的,你的代码没问题。为什么你认为它不起作用?
  • @AnthonyGeoghegan 我希望,现在,问题在编辑后得到了明确的定义!

标签: python list dictionary lowercase


【解决方案1】:

你可以再简化一点:

my_dict = {'some_key': ['A', 'B', 'C'], 'another_key': ['D', 'E', 'F']}

for key in my_dict:
    my_dict[key] = [x.lower() for x in my_dict[key]]

这样您就不必致电len()

【讨论】:

  • 我认为,我正在迭代字符串而不是字符!
  • 字符串是不可变的,所以你不能改变单个字符。
  • len() 真的很便宜。您正在创建新列表,而不是修改现有列表。
  • 这很好,这里是性能问题吗?
  • @Barmar 那么,lower() 是对字符串还是字符进行操作?
猜你喜欢
  • 2022-01-17
  • 1970-01-01
  • 2017-10-04
  • 2021-01-01
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多