问题描述
from array import *
val=array('u',["thili","gfgfdg"])
print(val)
当我在python代码上方进行编译时,编译器显示错误.
When I compiled above python code, the compiler showed an error.
我的代码有什么问题.无法在python数组中存储字符串?
What is the problem in my code.can not store strings in python array?
推荐答案
首先,Python解释器使用C语言编写,并且该数组库包含C语言数组(实际上,它不是Python数组,它是C的数组).字符串是C语言中的char数组(char是一个像一个字母的数字).您正在传递两个unicode字符串作为数组函数的参数,但是这些unicode字符串之一已经是C的数组.因此,您不能将两个unicode字符串传递给数组函数.看那个:
Firstly, the Python interpreter is written in C language language and that array library is includes array of C language (In fact, it is not array of Python, it is array of C). A string is array of chars in C (char is a number which act like one letter). You are passing two unicode strings as argument to the array function but one of these unicode strings is already an array for C. So you cant pass two unicode string to array function. Look at that:
from array import array
my_array = array("u","thili") # no error
print(my_array) # array('u', 'thili')
other_array = array("u",["thili","gfgfdg"])
Traceback (most recent call last):
File "<pyshell#5>", line 3, in <module>
my_array = array("u",["thili",""])
TypeError: array item must be unicode character
如您所见,unicode字符串数组与普通unicode字符串没有太大区别.因为它只包含一个字符串.您应该改为使用列表或元组类. Python中的列表类是Python数组.
As you can see array of unicode string is not much different than normal unicode string. Because it contains only one string.You should use list or tuple class instead. And the list class in Python is array of Python.
my_list = ["thili","gfgfdg"] # same as: my_list = list("thili","gfgfdg")
my_tuple = ("thili","gfgfdg") # same as: my_tuple = tuple("thili","gfgfdg")
不要忘记元组是不可变的,但列表是可变的.如果要更改任何索引的值,请使用列表.当您要优化内存(RAM)使用率时,元组是很好的选择.最后,在创建方面,元组比列表更快.
Dont forget that tuples are unmutable but lists are mutable. If you want to change value of any index, then use list.Tuples are good when you want to optimize your memory (RAM) usage. Finally tuples are more faster than lists in terms of creation.
这篇关于我可以在python数组中存储字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!