所以我正在尝试创建一个函数来跟踪调用方法的次数.例如:
a = [1,2,3,4]
a.pop()
Run Code Online (Sandbox Code Playgroud)
我想知道a.pop()到目前为止被调用了多少次,所以对于这个例子,我会得到1.有没有办法做到这一点?
我一直试图解决这个问题一段时间,我不能让它通过pep8.这是我的代码:
1.
if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')' and
sum(regex.count(char) for char in splitter) == 1 and
regex.count('(') == 1 and regex.count(')') == 1):
print('hi')
Run Code Online (Sandbox Code Playgroud)
2.
if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')' and
sum(regex.count(char) for char in splitter) == 1 and
regex.count('(') == 1 and regex.count(')') == 1):
print('hi')
Run Code Online (Sandbox Code Playgroud)
3.
if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')'
and regex.count('(') > 1):
print('hi')
Run Code Online (Sandbox Code Playgroud)
我在3个if语句中得到以下PEP8错误: …
def a(n):
return max([len(n)] + [a(i) for i in n]) if isinstance(n, list) else 0
Run Code Online (Sandbox Code Playgroud)
这是我最近的一次测试,我无法让列表理解得失败.所以基本上这个函数应该返回最大列表的长度(这是我假设基于正确的答案)我会理解,如果不是这部分函数:
+ [a(i) for i in n])
Run Code Online (Sandbox Code Playgroud)
当我看到那个部分时,看起来它增加了迭代的列表长度.有人可以阐明那部分的目的吗?更具体地说,添加的原因.
编辑:所以仔细看之后......看起来函数将第一个列表的长度放在一个列表中,然后放下下一个列表的长度并返回最大值?...这是如何工作的?
所以直到现在,我还是假设你有例如:
L = [1,2,3]
L2 = L1
L2.append(5)
Run Code Online (Sandbox Code Playgroud)
L和L2都会受到附加代码的影响.
但是,当您将L2指定为列表的副本时,例如:
L = [1,2,3]
L2 = L[:]
L2.append(5)
Run Code Online (Sandbox Code Playgroud)
只有L2会受到影响,而L仍然指的是[1,2,3]
但我现在遇到这个:
x = [1, 2]
L1 = [x, [8, 9]]
L2 = L1[:]
L2[0][1] = 999
>>>print(L1)
[[1,999],[8,9]]
>>>print(L2)
[[1,999],[8,9]]
Run Code Online (Sandbox Code Playgroud)
为什么在这种情况下,两个列表都改变了?
我有以下内容:
a = ['hello there good friend']
Run Code Online (Sandbox Code Playgroud)
我需要以下内容:
a = ['hello', 'there good', 'friend']
Run Code Online (Sandbox Code Playgroud)
基本上我需要它,所以列表的最后一个索引和第一个索引用逗号分隔,而其余的是一个单独的字符串.我已经尝试过为我的功能使用for循环,然而,它只是变成了一些非常混乱的东西,我认为这是反作用的.
我有:
letters = ['h','e','l','l','o']
Run Code Online (Sandbox Code Playgroud)
我需要:
'h e l l o'
Run Code Online (Sandbox Code Playgroud)
所以我尝试使用for循环如下:
new_str = ''
for str in letters:
new_str += str + ' '
Run Code Online (Sandbox Code Playgroud)
但结果是:
new_str = 'h e l l o '
Run Code Online (Sandbox Code Playgroud)
有没有办法在o之后没有空字符串?在我已经得到结果之后没有做某事.
对不起,我忘了提到是否有办法通过迭代列表来做到这一点.
我的命令是{str: {str: list of str}}
ex 的字典:
{'hii':{'bye': [1, 2]}}
Run Code Online (Sandbox Code Playgroud)
我想要的是:
{'hi':{'bye': [1, 2]}}
Run Code Online (Sandbox Code Playgroud)
有没有办法改变'hii'到只是'hi'?
我试过的只是编辑值而不是键.
我在格式中有以下表格
{str:list of str}
table1 = {key1:['1','2','3'], key2: ['3','4','5']}
table2 = {key3:['6','7','8','9'], key4:['9','10','11','12']}
Run Code Online (Sandbox Code Playgroud)
现在我需要在不使用itertools或sql命令的情况下获得两者的笛卡尔积.
我基本上需要新表:
new_table = {key1:['1','1','1','1','2','2','2','2','3','3','3','3'],
key2: ['3','3','3','3','4','4','4','4','5','5','5','5'],
key3: ['6','7','8','9','6','7','8','9'],
key4: ['9','10','11','12','9','10','11','12']}
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?