gpt4 book ai didi

python - 无需循环即可替换列表中的相同元素

转载 作者:行者123 更新时间:2023-12-02 16:08:00 25 4
gpt4 key购买 nike

我正在尝试用新字符串替换列表中所有相同的元素,并且还试图摆脱对所有内容使用循环。

# My aim is to turn:
list = ["A", "", "", "D"]
# into:
list = ["A", "???", "???", "D"]
# but without using a for-loop

我从理解的变体开始:

# e.g. 1
['' = "???"(i) for i in list]
# e.g. 2
list = [list[i] .replace '???' if ''(i) for i in range(len(lst))]

然后我尝试使用 Python 的 map 函数,如图 here :

list[:] = map(lambda i: "???", list)
# I couldn't work out where to add the '""' to be replaced.

最后我杀了一个third solution :

list[:] = ["???" if ''(i) else i for i in list]

我觉得我离合理的攻击路线更远了,我只是想要一种整洁的方式来完成一项简单的任务。

最佳答案

你可以试试这个:

list1 = ["A", "", "", "D"]

list2=list(map(lambda x: "???" if not x else x,list1))

print(list2)

这是上面那个的加长版:

list1 = ["A", "", "", "D"]
def check_string(string):
if not string:
return "???"
return string

list2=list(map(check_string,list1))
print(list2)

利用 "" 字符串是 False 值这一事实,您可以使用隐式 bool 值并分别返回值。输出:

['A', '???', '???', 'D']

关于python - 无需循环即可替换列表中的相同元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68863004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com