python-通过Pythonic方式降低列表中的字符串以及其他元素


def duplicate(inputList):
    inputList = [inputList for x in inputList if inputList[x] is str]
    print(inputList)

if __name__=='__main__':
    duplicate([1,2,3,2,1,3,"Hello","HeLlo"]);

我想降低所有字符串并在输入列表中找到重复项

使用 isinstance 检查元素类型:

[x.lower() if isinstance(x, str) else x for x in lst]
# [1, 2, 3, 2, 1, 3, 'hello', 'hello']

或:

[x.lower() if type(x) is str else x for x in lst]
# [1, 2, 3, 2, 1, 3, 'hello', 'hello']

如果你想从列表中找出独特的元素,你可以使用集合推导

{x.lower() if type(x) is str else x for x in lst}
# {1, 2, 3, 'hello'}

或获取重复项:

dupes = []
vals = set()
for x in lst:
    if isinstance(x, str):
        x = x.lower()
    if x in vals:
        dupes.append(x)
    else:
        vals.add(x)  
dupes
# [2, 1, 3, 'hello']

相关内容

最新更新