小编Edw*_*rlo的帖子

列表理解的意外输出

我有一个输入列表如下:

test_list = ['a', ('abc', 'd'), ['efgh', 'i'], 'jkl']
Run Code Online (Sandbox Code Playgroud)

我需要展平,所以摆脱元组和列表作为相应的第二和第三元素 test_list

预期产量:

['a', 'abc', 'd', 'efgh', 'i', 'jkl']
Run Code Online (Sandbox Code Playgroud)

我在找到正确的列表理解方面遇到了问题.我试过以下两个例子:

result = [xs if type(xs) is str else x for xs in test_list for x in xs]
print('result', result) 
# this outputs:
# ['a', 'abc', 'd', 'efgh', 'i', 'jkl', 'jkl', 'jkl']

result = [x if ((type(xs) is list) or (type(xs) is tuple)) else xs for xs in test_list for x in xs]
print('result',result)
#this also outputs:
# ['a', 'abc', 'd', 'efgh', …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension list python-3.x

4
推荐指数
1
解决办法
88
查看次数

在python中的def语句中使用' - >'有什么用?

看看这里给出的答案

例:

def md5_checksum_table(dir_name: str, suffix: str) -> {bytes: [str]}:
Run Code Online (Sandbox Code Playgroud)

这是我第一次看到->使用,我不明白这是做什么的.我试图在文档中搜索,但没有找到相关的描述.

任何人都可以向我解释这是/做什么的?

python python-3.x

2
推荐指数
1
解决办法
104
查看次数

列表中数字的总和

尝试编写一个带有如下列表的函数:

x = [1, 13, 14, 9, 8]
Run Code Online (Sandbox Code Playgroud)

例如,并将数字相加如下:

1 + (1+3) + (1+4) + 9 + 8 = 27       
Run Code Online (Sandbox Code Playgroud)

到目前为止我的尝试:

def sum_d(x):
    if not x:
        return 0
    else:
        return x[0] + sum_d(x[1:])
Run Code Online (Sandbox Code Playgroud)

python list python-3.x

-4
推荐指数
1
解决办法
1266
查看次数

标签 统计

python ×3

python-3.x ×3

list ×2

list-comprehension ×1