gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
Python groupby分组后每组随机抽取100个数
- User
Python groupby分组后每组随机抽取100个数
- Assistant
可以使用
groupby方法进行分组,然后使用sample方法随机抽取100个数。下面是一个例子:import random from itertools import groupby data = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] # 先按照条件分组 grouped_data = groupby(data, key=lambda x: x) # 随机抽取每组的100个数 result = [] for key, group in grouped_data: group = list(group) if len(group) < 100: result.extend(group) else: result.extend(random.sample(group, 100)) print(result)这段代码首先定义了一个列表
data,然后使用groupby方法按照元素的值进行分组。接下来使用循环遍历每个组,如果组的长度小于100,则将所有元素都加入到结果列表result中;否则使用random.sample方法从组中随机抽取100个元素,并将抽取的结果加入到result中。最后打印出结果。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.