据我所知,为了初始化一个数组,您可以这样调用:
from array import *
array_example = array([type of some sort],[entries into the array])
其中,某种类型的可以是整数之类的任何东西。我的问题是,在初始化数组时,是否有任何方法可以使用我定义的数据结构(字母)并使用该类型。你知道吗
以下是我尝试的:
x = Letter('A')
i = type(x)
array = array(i,[x])
然后我得到以下错误:
builtins.TypeError错误:array()参数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
正如您在docs中看到的,python
array
只能保存数值。你知道吗如文档所示,数组只能包含基本类型-整数、字节等
但似乎没有任何理由不能在这里使用列表。你知道吗
Python
array
可以与一组有限的预定义类型一起使用。不能将它们用于自定义类型。第一个参数实际上是单个字符,它指定数组将包含哪些允许的类型。见here。你知道吗相关问题 更多 >
编程相关推荐