简体   繁体   English

如何在 Python 中修改列表中的列表?

[英]How do i modify lists in lists in Python?

So, i'm trying to make my elements in my lists uppercase, but i can't make the standard something.upper(), i'm guessing because of the lists in the lists.所以,我试图使我的列表中的元素大写,但我无法使标准的 something.upper(),我猜测是因为列表中的列表。 fx:外汇:

names = [['henry', 'mike'],'jones', 'kevin',['michael', 'simon']]

How do i do this?我该怎么做呢?

Thank you谢谢

Check if the element is of type string of list检查元素是否为列表字符串类型

for i in names:
    if isinstance(i,list):
        for inner_element in i:
            print(inner_element.upper())
    elif isinstance(i,str): # to handle the case if ints are also present
        print(i.upper())

If you want to replace the values in existing list如果要替换现有列表中的值

for index,i in enumerate(names):
    if isinstance(i,list):
        temp=[]
        for inner_element in i:
            temp.append(inner_element.upper())
        names[index]=temp
    elif isinstance(i,str):
        names[index]=i.upper()

You can use list comprehensions as follows:您可以按如下方式使用列表推导式:

uppercase_names = [ name.upper() if isinstance(name, str) else [n.upper() for n in name if isinstance(n, str)] for name in names ]

Basically, we're using isinstance(name, str) to check if the object is actually a string object.基本上,我们使用isinstance(name, str)来检查对象是否实际上是字符串对象。

In case there are integers in the list, you can use this complex comprehension:如果列表中有整数,您可以使用这个复杂的理解:

uppercase_names = [ name.upper() if isinstance(name, str) else name if isinstance(name, int) else [ n.upper() if isinstance(n, str) else n if isinstance(n, int) else n for n in name ] for name in names ]

You could try this if the depth of the list is not known upfront.如果预先不知道列表的深度,您可以尝试此操作。

Input :输入

names=['jones', 'kevin', ['henry', 37, ['a', 0.69999]], ['michael', True]]

Function :功能

def recursive_upper(names):
 ret_list=[]
 for x in names:
     if isinstance(x, list):
         ret_list.append(recursive_upper(x))
     elif (isinstance(x, basestring) or isinstance(x, int) or isinstance(x, float) \
           or isinstance(x, long) or isinstance(x, bool) or isinstance(x, complex)):
         ret_list.append(str(x).upper())
 return ret_list

print recursive_func(names)

Output :输出

['JONES', 'KEVIN', ['HENRY', '37', ['A', '0.69999']], ['MICHAEL', 'TRUE']]

The function simply checks the type and recursively calls itself if type is a list.该函数只是检查类型,如果类型是列表,则递归调用自身。 It continues to return the uppercase version of text when it finds a string, int, float, long, bool or a complex type.当它找到字符串、int、float、long、bool 或复杂类型时,它会继续返回文本的大写版本。 All other types are simply ignored.所有其他类型都被简单地忽略。 (You could add/delete types in the elif condition. Refer here ) (您可以在 elif 条件中添加/删除类型。请参阅此处

Hope this helps :)希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM