2017-05-19 19 views
-3

我需要隨機選擇從類節點2個實例選擇實例:Python的 - 如何從任意一類

Class node:

類節點:

def __init__(self, parent = None, length_to_parent = None, name = None, left = None, right = None, internal = 1, root = 0): 
    self.parent = parent # parent node 
    self.length_to_parent = length_to_parent # length to the parent node 
    self.name = name # name of the node (to-be-defined name if external node(leaf), None if internal node) 
    self.left = left # left child 
    self.right = right # right child 
    self.internal = internal # indicate if the node is an internal node 
    self.root = root 

我想存儲來自列表中的節點的所有實例然後使用random.choose或random.shuffle從列表中隨機挑選2個節點。

但我不知道如何將實例存儲到列表中,儘管...任何人都請幫忙!謝謝

+0

我們都從某個地方開始,所以我會幫助您瞭解一些基本指導方針以獲得幫助。 1)發佈你的代碼片段(用ctrl + k縮進),屏幕截圖沒有幫助。 2)描述你做了什麼。 3)預期產出將有所幫助。 – Wboy

+0

您可以將對象保存在列表中:'[your_object()for _ in range(how_many_you_want)]',然後使用該列表中的random.select。 – dawg

回答

1

您可以像其他任何東西一樣將實例存儲在列表中。

import random 
lst = [] 
new_node = node(parent,length... etc) 

lst.append(new_node) 

# assuming you have > 2 nodes: 
# pick two random nodes, store in another lst 
random_selection = [random.choice(lst) for x in range(2)] 

有什麼具體的問題嗎?

+0

Yup注意到了,謝謝@abccd – Wboy

+0

是的,這是更好,upvoted,但是爲了改善,你還可以添加另一個例子'random.choices(lst,k = 2)',並指定它只適用於python 3.6 :) – abccd

+0

@abccd That's true !謝謝你分享你的知識:) – Wboy

0

我假設你的這個「節點」是二叉樹的一部分。 在這種情況下,您可以遍歷樹並將引用存儲在運行列表中。

東西線沿線的:

arr = [] 
# Perform tree traversal. 
traverse(root_node, arr) 
# Now, do something here with the list! 

def traverse(node, arr): 
    # Traverse the left subtree 
    if(node.left is not None): 
     traverse(node.left, arr) 
    # Traverse the right subtree 
    if(node.right is not None): 
     traverse(node.right, arr) 
    # Append the node! It can be appended like any other item in the list. 
    arr.append(node) 

你應該能夠追加節點(如其他東西)的列表,然後選擇您隨機元素的要求。

+2

請不要校對列表'列表'。您可以用相同的名稱覆蓋該功能。 – dawg

+0

哎呀,很好的@dawg!我不是主要的Python開發者:)編輯! – rageandqq

0

我想補充一類變量保存的所有節點(這是在__init__末增加),以及一類方法隨機獲得二:

import random 

class Node: 
    node_instances = [] 
    def __init__(self, parent = None, length_to_parent = None, name = None, left = None, right = None, internal = 1, root = 0): 
     self.parent = parent # parent node 
     self.length_to_parent = length_to_parent # length to the parent node 
     self.name = name # name of the node (to-be-defined name if external node(leaf), None if internal node) 
     self.left = left # left child 
     self.right = right # right child 
     self.internal = internal # indicate if the node is an internal node 
     self.root = root 
     Node.node_instances.append(self) 

    @classmethod 
    def get_random_instances(cls): 
     return random.sample(cls.node_instances, 2) 

,您可以使用這樣的:

相關問題