【发布时间】:2017-04-15 04:48:38
【问题描述】:
我有二维列表:
list=[["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]]
我想要的输出是:
new_list=[["hello", "my", "world"], ["my", "your", "ours"]]
【问题讨论】:
标签: python python-3.x
我有二维列表:
list=[["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]]
我想要的输出是:
new_list=[["hello", "my", "world"], ["my", "your", "ours"]]
【问题讨论】:
标签: python python-3.x
您可以使用包含另一个列表推导作为其元素的列表推导来做到这一点。这一切的根源是调用str.lower() 来创建新的小写字符串。
除此之外:最好不要在内置类型之后命名变量。尝试使用my_list=、lst= 或诸如mixed_case_words= 之类的描述性名称,而不是list=
new_list = [ [ item.lower() for item in sublist ] for sublist in old_list]
如果您更喜欢循环,可以使用嵌套的for 循环:
new_list = []
for sublist in old_list:
new_sublist = []
for item in sublist:
new_sublist.append(item.lower())
new_list.append(new_sublist)
【讨论】:
你可以试试这个:
list=[["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]]
new_list = [ [ i.lower() for i in innerlist ] for innerlist in list]
print(new_list)
输出:
[['hello', 'my', 'world'], ['my', 'your', 'ours']]
【讨论】:
嵌套列表理解将适用于您的情况
lst = [["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]]
new_lst = [ [i.lower() for i in j] for j in lst]
# [["hello", "my", "world"], ["my", "your", "ours"]
我们也可以使用eval 和str 方法执行以下操作,这将处理任何深度的字符串嵌套列表
lst = [["Hello", "mY", "WORLD"], ["MY", "yOur", "ouRS"]]
# replace eval with ast.literal_eval for safer eval
new_lst = eval(str(lst).lower())
# [["hello", "my", "world"], ["my", "your", "ours"]
【讨论】: