相关疑难解决方法(0)

将元组扩展为参数

有没有办法将Python元组扩展为函数 - 作为实际参数?

例如,这里expand()有魔力:

some_tuple = (1, "foo", "bar")

def myfun(number, str1, str2):
    return (number * 2, str1 + str2, str2 + str1)

myfun(expand(some_tuple)) # (2, "foobar", "barfoo")
Run Code Online (Sandbox Code Playgroud)

我知道可以定义myfunmyfun((a, b, c)),但当然可能有遗留代码.谢谢

python tuples parameter-passing

375
推荐指数
5
解决办法
20万
查看次数

获取一系列列表的笛卡尔积?

如何从一组列表中获取笛卡尔积(每种可能的值组合)?

输入:

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]
Run Code Online (Sandbox Code Playgroud)

期望的输出:

[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...]
Run Code Online (Sandbox Code Playgroud)

python list cartesian-product

289
推荐指数
9
解决办法
18万
查看次数

用Python解压缩列表?

我认为'解包'可能是错误的词汇 - 道歉,因为我确信这是一个重复的问题.

我的问题很简单:在一个需要项目列表的函数中,如何在不出错的情况下传递Python列表项?

my_list = ['red', 'blue', 'orange']
function_that_needs_strings('red', 'blue', 'orange') # works!
function_that_needs_strings(my_list) # breaks!
Run Code Online (Sandbox Code Playgroud)

当然必须有一种方法来扩展列表,并'red','blue','orange'在蹄上传递函数?

python list argument-passing

189
推荐指数
3
解决办法
17万
查看次数

函数调用中的星号

我正在使用itertools.chain以这种方式"压扁"列表列表:

uniqueCrossTabs = list(itertools.chain(*uniqueCrossTabs))
Run Code Online (Sandbox Code Playgroud)

这有什么不同于说:

uniqueCrossTabs = list(itertools.chain(uniqueCrossTabs))
Run Code Online (Sandbox Code Playgroud)

python operators

105
推荐指数
3
解决办法
4万
查看次数

itertools:排列的笛卡尔乘积

使用pythons itertools,我想在一堆列表的所有排列的外积上创建一个迭代器.一个明确的例子:

import itertools
A = [1,2,3]
B = [4,5]
C = [6,7]

for x in itertools.product(itertools.permutations(A),itertools.permutations(B),itertools.permutations(C)):
    print x
Run Code Online (Sandbox Code Playgroud)

虽然这有效,但我想将其推广到任意列表列表.我试过了:

for x in itertools.product(map(itertools.permutations,[A,B,C])):
    print x
Run Code Online (Sandbox Code Playgroud)

但它并没有按照我的意图行事.预期的产出是:

((1, 2, 3), (4, 5), (6, 7))
((1, 2, 3), (4, 5), (7, 6))
((1, 2, 3), (5, 4), (6, 7))
((1, 2, 3), (5, 4), (7, 6))
((1, 3, 2), (4, 5), (6, 7))
((1, 3, 2), (4, 5), (7, 6))
((1, 3, 2), (5, 4), (6, 7))
((1, 3, 2), …
Run Code Online (Sandbox Code Playgroud)

python permutation cartesian-product python-itertools

3
推荐指数
1
解决办法
1851
查看次数

如何在python中优化以下算法的内存和时间使用

我试图在Python中完成以下逻辑操作,但进入内存和时间问题.既然,我是python的新手,那么如何以及在哪里优化问题的指导将不胜感激!(我明白以下问题有点抽象)

import networkx as nx 
    dic_score = {}
    G = nx.watts_strogatz_graph(10000,10,.01) # Generate 2 graphs with 10,000 nodes using Networkx
    H = nx.watts_strogatz_graph(10000,10,.01)
    for Gnodes in G.nodes()
        for Hnodes in H.nodes ()  # i.e. For all the pair of nodes in both the graphs
           score = SomeOperation on (Gnodes,Hnodes)  # Calculate a metric 
           dic_score.setdefault(Gnodes,[]).append([Hnodes, score, -1 ]) # Store the metric in the form a Key: value, where value become a list of lists, pair in a dictionary
Run Code Online (Sandbox Code Playgroud)

然后根据此处提到的条件sorted_criterion …

python memory sorting performance networkx

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