Py学习  »  Python

如何在Python中对列表中的字符串执行方法

lastwords • 4 年前 • 1128 次点击  

list_in_list = all_lists[0] #prints first list
string_in_list = list_in_list[0] #prints string in first list

我想创建一个for循环,它允许我用一个方法改变所有字符串,并将它们放回列表中,并将所有列表放回all_列表中。这就是我现在所拥有的:

new_list = []
for i in range(len(all_lists)): # all lists
    list_in_list = all_lists[i] # separate lists from all_lists
    for j in range(len(list_in_list)): # every list in all_list
        string_in_list = line[j] # separate string from list
        new_string = decontracted(string_in_list) # apply the method on string
        new_list.append(new_string) # put new string back in a list

我不确定如何将每个列表放回包含所有列表的列表中。有人能帮我吗?

例如,如果该方法将每个字符串大写:

发件人:

[['list one'],['list two'],['list...'],['list n']]

致:

[['LIST ONE'],['LIST TWO'],['LIST...'],['LIST N']]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55955
 
1128 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Austin
Reply   •   1 楼
Austin    4 年前

您可以使用 map :

list(map(lambda x: [x[0].upper()], lst))

:

lst = [['list one'],['list two'],['list...'],['list n']]

print(list(map(lambda x: [x[0].upper()], lst)))
# [['LIST ONE'], ['LIST TWO'], ['LIST...'], ['LIST N']]

这不受限制;我们可以应用任何自定义函数来转换列表中的元素,例如:

list(map(decontracted, lst))
PacketLoss
Reply   •   3 楼
PacketLoss    4 年前

你可以用 for loops list comprehension 在你的例子中实现这个结果。

all_lists = [['list one'],['list two'],['list...'],['list n']]

作为一个函数,我们可以执行 upper 对于列表中的每个元素,使用 for loop .

def upper_list(data):
    result = []
    for nested in data:
        changes = []
        for element in nested:
            changes.append(element.upper())
        result.append(changes)
    return result

upper_list(all_lists)
#[['LIST ONE'], ['LIST TWO'], ['LIST...'], ['LIST N']]

此外,您可以使用列表理解将上述内容压缩成一行代码。

all_lists = [[element.upper() for element in nested] for nested in all_lists]

这两种方法都适用于包含多个元素的嵌套列表,例如;

all_lists = [['list one', 'test'],['list two','two'],['list...'],['list n']]

>>>[[element.upper() for element in nested] for nested in all_lists]
#[['LIST ONE', 'TEST'], ['LIST TWO', 'TWO'], ['LIST...'], ['LIST N']]