我有一个整数列表,我想生成一个包含所有连续整数列表的列表.
#I have:
full_list = [0,1,2,3,10,11,12,59]
#I want:
continuous_integers = [[0,1,2,3], [10,11,12], [59]]
Run Code Online (Sandbox Code Playgroud)
我有以下工作,但似乎是一个糟糕的方式:
sub_list = []
continuous_list = []
for x in full_list:
if sub_list == []:
sub_list.append(x)
elif x-1 in sub_list:
sub_list.append(x)
else:
continuous_list.append(sub_list)
sub_list = [x]
continuous_list.append(sub_list)
Run Code Online (Sandbox Code Playgroud)
我已经看到其他问题表明itertools.groupby是一种有效的方法,但是我不熟悉这个函数,我似乎在编写lambda函数来描述连续性时遇到了麻烦.
问题:有没有更好的方法(可能使用itertools.groupby?)
注意事项:full_list将包含1到59个整数,将始终排序,整数将介于0到59之间.
如何有效地将已排序的numpy数组中的相同元素移动到子数组中?
从这里:
import numpy as np
a=np.array([0,0,1,1,1,3,5,5,5])
Run Code Online (Sandbox Code Playgroud)
到这里:
a2=array([[0, 0], [1, 1, 1], [3], [5, 5, 5]], dtype=object)
Run Code Online (Sandbox Code Playgroud) 以下简单代码为我提供了200个元素的长度3的可能组合。
from itertools import combinations
comb = combinations( range(200), 3 )
Run Code Online (Sandbox Code Playgroud)
我想以随机顺序获取组合,以便选择前N个组合。但是,如果我将梳子转换为一个列表并按如下所示对其进行混洗,则可能会出现内存错误,因为该列表可能包含太多元素:
comb = list(comb) # This might be huge and give a memory error
random.shuffle(comb)
N = 10
comb = comb[:10] # get only the first N random combinations
Run Code Online (Sandbox Code Playgroud)
还有其他方法可以获取N个随机组合吗?(即,不是按照itertools.combinations生成的顺序)。
说我有以下三个列表:
aList = [1,2,3,4,5,6]
bList = ['a','b','c','d']
cList = [1,2]
Run Code Online (Sandbox Code Playgroud)
我想使用来遍历它们zip。
通过如下方式使用循环zip:
from itertools import cycle
for a,b,c in zip(aList, cycle(bList), cycle(cList)):
print a,b,c
Run Code Online (Sandbox Code Playgroud)
我得到的结果是:
1 a 1
2 b 2
3 c 1
4 d 2
5 a 1
6 b 2
Run Code Online (Sandbox Code Playgroud)
虽然我希望我的结果像:
1 a 1
2 b 1
3 c 1
4 d 1
5 a 2
6 b 2
Run Code Online (Sandbox Code Playgroud) 我正试图在hackerrank比赛中找到一个有趣的问题,并且出现了这个问题.我使用itertools,这是代码:
import itertools
l = []
for _ in range(int(input())):
l.append(int(input()))
max = l[0] * l[len(l)-1]
for a,b in itertools.combinations(l,2):
if max < (a*b):
max = (a*b)
print(max)
Run Code Online (Sandbox Code Playgroud)
他们还有其他任何有效的方法吗?因为我在一些我无法访问的测试用例中得到时间错误(因为它是一个小小的竞赛).
我想使用itertools的各种函数来创建numpy数组.我可以很容易地提前计算产品中元素的数量,组合,排列等,因此分配空间不应该是一个问题.
例如
coords = [[1,2,3],[4,5,6]]
iterable = itertools.product(*coords)
shape = (len(coords[0]), len(coords[1]))
arr = np.iterable_to_array(
iterable,
shape=shape,
dtype=np.float64,
count=shape[0]*shape[1]
) #not a real thing
answer = np.array([
[1,4],[1,5],[1,6],
[2,4],[2,5],[2,6],
[3,4],[3,5],[3,6]])
assert np.equal(arr, answer)
Run Code Online (Sandbox Code Playgroud) 在Python中,我可以执行以下操作:
from itertools import product
k = 3
for kmer in product("AGTC", repeat=k):
print(kmer)
Run Code Online (Sandbox Code Playgroud)
在Rust中,我可以k=3通过以下方式强制行为:
#[macro_use] extern crate itertools;
for kmer in iproduct!("AGTC".chars(), "AGTC".chars(), "AGTC".chars()){
println!("{:?}", kmer);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我想要k=4或k=5怎么办?
我希望获得两个不同元素的所有可能排列,这两个元素按四个分组而不重复输出但是重复元素(显然你需要重复元素来组合4只有2个元素).
所以,我试过的一些事情:
sorted(list(map(lambda x: "".join(x), list(permutations('AB', 4)))))
Run Code Online (Sandbox Code Playgroud)
返回一个空列表.所以我尝试了这个:
sorted(list(map(lambda x: "".join(x), list(permutations('AABB', 4)))))
Run Code Online (Sandbox Code Playgroud)
并且它对我期望的输出是封闭的,但是充满了多余的项目,只有少数:
['AABB','AABB','AABB','AABB','ABAB','ABAB','ABAB',...
Run Code Online (Sandbox Code Playgroud)
我期望得到的实际上是:
['AABB','ABAB','ABBA','BAAB','BABA','BBAA']
Run Code Online (Sandbox Code Playgroud)
我也试过combination()和product()而不是permutations()但没有成功,但也许我的论点不适合这个问题.
有任何想法吗?
非常感谢提前!
PS.正如Antoine所指出的,有一个使用集合而不是列表的解决方法,例如:
sorted(list(map(lambda x: "".join(x), set(permutations('AABB', 4)))))
Run Code Online (Sandbox Code Playgroud)
这给出了预期的输出,但仍然产生了所有的重复,但恰好被过滤掉了,因为集合不能有重复的元素,所以它可能不是最有效的方法.
我正在寻找一种Pythonic方式或更有效的方法来解决这个问题.我有一个字典,其中设置为值(跨键允许重复).给定一个列表,我必须创建一个字典,使用主字典中的键将每个类别映射到元素.我举一个例子来说明.
大师词典
{
"KeyA": ['Aron', 'Ranom Value', 'Abhishek'],
"KeyB": ['Ball', 'Foo', 'Bar', 'Badge', 'Dog'],
"KeyZ": ['Random Value', 'Foo', 'Bar']
}
Run Code Online (Sandbox Code Playgroud)
输入
['Foo', 'Bar', 'Dog', 'Aron']
Run Code Online (Sandbox Code Playgroud)
产量
{
"KeyA": ['Aron'],
"KeyB": ['Bar', 'Foo', 'Dog'],
"KeyZ": ['Foo', 'Bar']
}
Run Code Online (Sandbox Code Playgroud)
将集合中的单个项目反转为键,然后执行查找.
{
'Aron' : ['KeyA'],
'Foo' : ['KeyB', 'KeyZ'],
'Bar' : ['KeyB', 'KeyZ'],
'Random Value' : ['KeyA', 'KeyZ']
}
Run Code Online (Sandbox Code Playgroud)
我通过遍历每一组中的每一项来初始化倒置的字典.创建这样的字典的大约时间是O(n).在如此创建的反向字典中查找列表中的项目.说出价值Bar.使用该信息创建新词典'Bar': ['KeyB', 'KeyZ'].结果词典将是{'KeyB': ['Bar'], 'KeyZ': ['Bar']}.对于下一个项目,我必须在现有字典上进行一些簿记,如是否存在密钥,如果是,则附加到现有列表,依此类推.
使用映射的集合中的in运算符(检查成员资格)到每个键
主词典和输入列表在大多数时候都会非常小.(所有套装中的独特物品少于500件).所以我可以检查每个键返回的集合的成员资格并创建一个字典.这显然效率较低,但适用于大多数情况.
我还有一些类似于上面给出的例子的操作.我不想为所有这些操作进行手动记账,因为它们容易出错并且比内置功能慢.
我需要的?
虽然这很简单,但遗憾的是,事实并非如此.
我正在尝试构建一个函数来获取可迭代的字典(即,一个唯一的字典列表)并返回字典的唯一分组列表的列表.
x球员,我想组建k一支n规模很大的球队.来自CMSDK的这个问题和一组答案是我能找到的解决方案最接近的问题.为了使它从处理字母串到词典,我发现我的Python技能不足.
我正在改编的原始功能来自第二个答案:
import itertools as it
def unique_group(iterable, k, n):
"""Return an iterator, comprising groups of size `k` with combinations of size `n`."""
# Build separate combinations of `n` characters
groups = ("".join(i) for i in it.combinations(iterable, n)) # 'AB', 'AC', 'AD', ...
# Build unique groups of `k` by keeping the longest sets of characters
return (i for i in it.product(groups, repeat=k)
if len(set("".join(i))) == sum((map(len, i)))) # …Run Code Online (Sandbox Code Playgroud) python ×10
python-itertools ×10
algorithm ×2
combinations ×2
dictionary ×2
group-by ×2
numpy ×2
arrays ×1
continuous ×1
cycle ×1
lambda ×1
math ×1
permutation ×1
python-2.7 ×1
python-3.x ×1
rust ×1
shuffle ×1
zip ×1