从Python中的列表中提取随机子列表

时间:2015-11-25 06:38:44

标签: python random sublist

我有一个python字典如下:

a_list = a_dict.get('APPLE_PROVIDERS', "")
for item in a_list[randrange(0,len(a_list)) : randrange(0,len(a_list))]:
  ...do something.. 

我想要做的是从密钥列表中获取一个随机子列表(这是一个值)。不仅仅是一个元素,而是一个完全随机的子列表。这是我试过的:

<?php
echo $this->Html->link('Add', array('controller'=>'carts', 
'action'=>'add', 'product_id'=>$product['Product']['id']),
array('class'=>'btn btn-primary col-md-offset-4', 
'data-product-id'=>$product['Product']['id']));
?>

$('a.btn').on('click', function(e){
        var this = $(this);
        var product_id = this.data('product-id');
        this.html('Item Added');

        $.ajax({
            url: '/cartphp_cart/carts/add/',
            type: 'POST',
            data: {product_id: product_id},
            success: function(count) {
                $('#number-of-items').text(' ' + count);
                console.log(count);
            }
        });
        e.preventDefault();
    });

这件事有两个问题:

  1. 如果列表为空,或者dict查找失败,程序将失败,因为randrange有(0,0)作为参数,这会导致错误

  2. 很多时候,两个randrange()调用都会生成相同的数字,尤其是当列表很小时。这将返回一个空列表。例如a_list [5:5]

  3. 那么处理上述案例的随机子列表的最佳方法是什么?另外,我不关心订购。一切正常。每次for循环开始时,我只想要一个完全随机的子列表0,1 ...直到len(a_list)元素。

    如果列表可以在其他可以容纳类似元素的数据结构中更改,那么这对我也有用。

4 个答案:

答案 0 :(得分:16)

示例。

>>> random.sample(["some", "provider", "can", "be", "null"], 3)
['some', 'can', 'provider']
>>> random.sample(["some", "provider", "can", "be", "null"], 3)
['can', 'null', 'provider']
>>> random.sample(["some", "provider", "can", "be", "null"], 3)
['null', 'some', 'provider']

答案 1 :(得分:4)

>>> from random import randint
>>> left = randint(0, len(L))
>>> right = randint(left, len(L))
>>> L[left:right]
['null']

如果你不想要空列表的可能性

>>> left = randint(0, len(L) - 1)
>>> right = randint(left + 1, len(L))

答案 2 :(得分:1)

Ignacio's answer很棒。如果您想最低限度地修改代码,可以这样做:

Sub CopyData()

    Dim fileDialog As fileDialog
    Dim strPathFile As String
    Dim strFileName As String
    Dim strPath As String
    Dim dialogTitle As String
    Dim wbSource As Workbook
    Dim rngToCopy As Range
    Dim rngRow As Range
    Dim rngDestin As Range
    Dim lngRowsCopied As Long


    dialogTitle = "Navigate to and select required file."
    Set fileDialog = Application.fileDialog(msoFileDialogFilePicker)
    With fileDialog
        .InitialFileName = "P:\Sales & Marketing\REVENUE MANAGEMENT\REPORTS"
        '.InitialFileName = ThisWorkbook.Path & "\" 'Alternative to previous line
       .AllowMultiSelect = False
        .Filters.Clear
        .Title = dialogTitle



        If .Show = False Then
            MsgBox "File not selected to import. Process Terminated"
            Exit Sub
        End If
        strPathFile = .SelectedItems(1)
    End With

    Set wbSource = Workbooks.Open(Filename:=strPathFile)

    Range("16:16,18:18,20:20,22:22,24:24,26:26").Select
    Range("A26").Activate
    ActiveWindow.ScrollRow = 10
    ActiveWindow.ScrollRow = 11
    ActiveWindow.ScrollRow = 12
    ActiveWindow.ScrollRow = 13
    ActiveWindow.ScrollRow = 14
    ActiveWindow.ScrollRow = 15
    ActiveWindow.ScrollRow = 16
    ActiveWindow.ScrollRow = 17
    ActiveWindow.ScrollRow = 18
    ActiveWindow.ScrollRow = 19
    ActiveWindow.ScrollRow = 20
    ActiveWindow.ScrollRow = 21
    ActiveWindow.ScrollRow = 22
    ActiveWindow.ScrollRow = 23
    ActiveWindow.ScrollRow = 24
    ActiveWindow.ScrollRow = 25
    ActiveWindow.ScrollRow = 26
    ActiveWindow.ScrollRow = 25
    ActiveWindow.ScrollRow = 24
    ActiveWindow.ScrollRow = 23
    ActiveWindow.ScrollRow = 22
    Range( _
        "16:16,18:18,20:20,22:22,24:24,26:26,28:28,30:30,32:32,34:34,36:36,38:38,40:40,42:42,44:44,46:46" _
        ).Select
    Range("A46").Activate
    ActiveWindow.ScrollRow = 23
    ActiveWindow.ScrollRow = 24
    ActiveWindow.ScrollRow = 25
    ActiveWindow.ScrollRow = 26
    ActiveWindow.ScrollRow = 27
    ActiveWindow.ScrollRow = 28
    ActiveWindow.ScrollRow = 29
    ActiveWindow.ScrollRow = 30
    ActiveWindow.ScrollRow = 31
    ActiveWindow.ScrollRow = 32
    ActiveWindow.ScrollRow = 33
    ActiveWindow.ScrollRow = 34
    ActiveWindow.ScrollRow = 35
    ActiveWindow.ScrollRow = 36
    ActiveWindow.ScrollRow = 37
    ActiveWindow.ScrollRow = 38
    ActiveWindow.ScrollRow = 39
    ActiveWindow.ScrollRow = 40
    ActiveWindow.ScrollRow = 41
    ActiveWindow.ScrollRow = 42
    Range( _
        "16:16,18:18,20:20,22:22,24:24,26:26,28:28,30:30,32:32,34:34,36:36,38:38,40:40,42:42,44:44,46:46,48:48,50:50,52:52,54:54,56:56,58:58,60:60,62:62,64:64,66:66,68:68" _
        ).Select
    Range("A68").Activate
    ActiveWindow.ScrollRow = 41
    ActiveWindow.ScrollRow = 43
    ActiveWindow.ScrollRow = 44
    ActiveWindow.ScrollRow = 46
    ActiveWindow.ScrollRow = 48
    ActiveWindow.ScrollRow = 50
    ActiveWindow.ScrollRow = 53
    Range( _
        "16:16,18:18,20:20,22:22,24:24,26:26,28:28,30:30,32:32,34:34,36:36,38:38,40:40,42:42,44:44,46:46,48:48,50:50,52:52,54:54,56:56,58:58,60:60,62:62,64:64,66:66,68:68,70:70,72:72,74:74" _
        ).Select
    Range("A74").Activate
    Selection.Delete Shift:=xlUp
    Range("F64").Select
    ActiveWindow.SmallScroll Down:=-48
    Range("A15:P45").Select
    Selection.Copy

    Set rngDestin = ThisWorkbook.Sheets("RawData").Range("A2").PasteSpecial


    wbSource.Close SaveChanges:=False

    Set fileDialog = Nothing
    Set rngRow = Nothing
    Set rngToCopy = Nothing
    Set wbSource = Nothing
    Set rngDestin = Nothing

    'MsgBox "The Data Is Imported"

End Sub

我在这里做了两件事:1)我检查a_list是否有多个元素,2)我使用randrange生成索引,但是第二种方式保证大于第一个。< / p>

答案 3 :(得分:1)

因此,假设您希望在获得空列表时返回空列表,这是一个示例解决方案:

from random import shuffle

def get_random_sublist(the_dict, key, number):
    l = the_dict.get(key, [])
    shuffle(l)
    return l[:number]

所以,我会使用random.shuffle。这使我可以避免要求一个比我们得到的实际列表更大的子列表的问题。

>>> DICT = {'a' : "1 2 3 4 5".split(), 'b': [], 'c': [1]}
>>> get_random_sublist(DICT, 'a', 3)
['4', '1', '2']
>>> get_random_sublist(DICT, 'b', 10)
[]
相关问题