從我爲了初始化數組瞭解創建數組,你會叫這樣的:用自己的數據結構
from array import *
array_example = array([type of some sort],[entries into the array])
其中類型某種的可以是任何東西,如一個整數。我的問題是,如果我有任何方式使用我定義的數據結構(Letter)並在初始化數組時使用該類型。
這裏是我的嘗試:
x = Letter('A')
i = type(x)
array = array(i,[x])
,我然後得到了以下錯誤:
builtins.TypeError:陣列()參數1必須是Unicode字符,而不是鍵入
很抱歉,如果這是一個愚蠢的問題
class Letter:
def __init__(self, letter):
"""
-------------------------------------------------------
Initialize a Letter object.
Use: l = Letter(char)
-------------------------------------------------------
Preconditions:
letter - an single uppercase letter of the alphabet (str)
Postconditions:
Letter values are set.
-------------------------------------------------------
"""
assert letter.isalpha() and letter.isupper(), "Invalid letter"
self.letter = letter
self.count = 0
self.comparisons = 0
return
def __str__(self):
"""
-------------------------------------------------------
Creates a formatted string of Letter data.
Use: print(m)
Use: s = str(m)
-------------------------------------------------------
Postconditions:
returns:
the value of self.letter (str)
-------------------------------------------------------
"""
return "{}: {}, {}".format(self.letter, self.count, self.comparisons)
def __eq__(self, rs):
"""
-------------------------------------------------------
Compares this Letter against another Letter for equality.
Use: l == rs
-------------------------------------------------------
Preconditions:
rs - [right side] Letter to compare to (Letter)
Postconditions:
returns:
result - True if name and origin match, False otherwise (boolean)
-------------------------------------------------------
"""
self.count += 1
self.comparisons += 1
result = self.letter == rs.letter
return result
def __lt__(self, rs):
"""
-------------------------------------------------------
Determines if this Letter comes before another.
Use: f < rs
-------------------------------------------------------
Preconditions:
rs - [right side] Letter to compare to (Letter)
Postconditions:
returns:
result - True if Letter precedes rs, False otherwise (boolean)
-------------------------------------------------------
"""
self.comparisons += 1
result = self.letter < rs.letter
return result
def __le__(self, rs):
"""
-------------------------------------------------------
Determines if this Letter precedes or is or equal to another.
Use: f <= rs
-------------------------------------------------------
Preconditions:
rs - [right side] Letter to compare to (Letter)
Postconditions:
returns:
result - True if this Letter precedes or is equal to rs,
False otherwise (boolean)
-------------------------------------------------------
"""
self.comparisons += 1
result = self.letter <= rs.letter
return result