gpt4 book ai didi

python - 代码审查 : Python list concatenation elements to string

转载 作者:行者123 更新时间:2023-12-01 03:16:56 24 4
gpt4 key购买 nike

嘿,我有一个问题,正在解决一个问题看起来像这样:

输出正是我所需要的,但我想知道是否没有更优雅的如何做到这一点?

list = [["key189","0","apples"],
["key622","1","bananas"],
["key233","2","bacon"],
["key454","3","bread"],
["key35","4","jam"],
["key6","5","coffee"]]

for e in list:
if e[0] == "key622":
key622 = e[2]
if e[0] == "key189":
key189 = e[2]
if e[0] == "key35":
key35 = e[2]
if e[0] == "key454":
key454 = e[2]
if e[0] == "key233":
key233 = e[2]
if e[0] == "key6":
key6 = e[2]

string_form = "|".join([key6, key35, key233, key189, key622, key454])


print(string_form)
# prints coffee|jam|bacon|apples|bananas|bread

最佳答案

我认为使用字典会让你的生活更轻松。

dt = {itm[0]:itm[2] for itm in list}

dt 将是:

{'key189': 'apples',
'key233': 'bacon',
'key35': 'jam',
'key454': 'bread',
'key6': 'coffee',
'key622': 'bananas'}

string_form = "|".join(dt.values())

string_form 将是:

'coffee|apples|bacon|jam|bananas|bread'

你可以获得任何键的值:像这样:

dt.get('key35')

对于特定字符串,请使用:

"|".join([dt.get('key6'), dt.get('key35'), dt.get('key233'), dt.get('key189'), dt.get('key622'), dt.get('key454')])

尽量不要使用listdict等变量名

关于python - 代码审查 : Python list concatenation elements to string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42392351/

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