在Python中高效生成百万元素的随机列表

3 投票
3 回答
2055 浏览
提问于 2025-04-16 09:36

我看过这个回答,觉得它可能是用Python随机打乱字符串列表的最佳方法。我只是想知道,这是否是最有效的方法,因为我有一个大约3000万个元素的列表,代码如下:

import json
from sets import Set
from random import shuffle

a = []

for i in range(0,193):
    json_data = open("C:/Twitter/user/user_" + str(i) + ".json")
    data = json.load(json_data)
    for j in range(0,len(data)):
        a.append(data[j]['su'])
new = list(Set(a))
print "Cleaned length is: " + str(len(new))

## Take Cleaned List and Randomize it for Analysis
shuffle(new)

如果有更有效的方法,我非常感谢任何建议。

谢谢,

3 个回答

0

我不知道这样做是否会更快,但你可以试试 numpy的shuffle功能

2

如果你想要对文件进行随机打乱,那你最好使用这个文件里的解决方案。真的,别犹豫。

随机打乱一个有三百万行的文件

简单来说,打乱算法的周期非常短(这意味着它无法覆盖三百万行文件的所有可能组合,更别提三千万行了)。如果你能把数据加载到内存中,那么按照他们说的做是最好的选择。基本上就是给每一行分配一个随机数,然后把这些行按照随机数排序。

你可以看看这个讨论。还有,我已经为你做了这个,以免你搞错(这是个玩笑),

import json
import random
from operator import itemgetter

a = set()
for i in range(0,193):
    json_data = open("C:/Twitter/user/user_" + str(i) + ".json")
    data = json.load(json_data)
    a.update(d['su'] for d in data)

print "Cleaned length is: " + str(len(new))

new = [(random.random(), el) for el in a]
new.sort()
new = map(itemgetter(1), new)
4

这里有几个可能的建议:

import json
from random import shuffle

a = set()
for i in range(193):
    with open("C:/Twitter/user/user_{0}.json".format(i)) as json_data:
        data = json.load(json_data)
        a.update(d['su'] for d in data)

print("Cleaned length is {0}".format(len(a)))

# Take Cleaned List and Randomize it for Analysis
new = list(a)
shuffle(new)

.

  • 要知道哪个更快,唯一的方法就是进行性能测试!
  • 你有特别的原因喜欢使用sets.Set而不是内置的set()吗?
  • 我引入了一个with语句(这是打开文件的推荐方式,因为它能确保文件被关闭)
  • 看起来你只是把'a'这个列表转换成了一个集合;为什么不一开始就直接用集合呢?
  • 与其通过索引来遍历,然后再根据索引查找,不如直接遍历数据项...
  • 这样就很容易改写成生成器表达式了

撰写回答