在python中创建字符串数组的最佳方法是什么?

时间:2022-06-14 21:41:13

I'm relatively new to Python and it's libraries and I was wondering how I might create a string array with a preset size. It's easy in java but I was wondering how I might do this in python.

我对Python和它的库相对较新,我想知道如何创建一个预设大小的字符串数组。它在java中很容易,但我想知道如何在python中执行此操作。

So far all I can think of is

到目前为止,我能想到的是

strs = ['']*size

And some how when I try to call string methods on it, the debugger gives me an error X operation does not exist in object tuple.

还有一些当我尝试在其上调用字符串方法时,调试器给出了一个错误X对象元组中不存在操作。

And if it was in java this is what I would want to do.

如果是在java中,这就是我想要做的。

String[] ar = new String[size];
Arrays.fill(ar,"");

Please help.

请帮忙。

Error code

错误代码

    strs[sum-1] = strs[sum-1].strip('\(\)')
AttributeError: 'tuple' object has no attribute 'strip'

Question: How might I do what I can normally do in Java in Python while still keeping the code clean.

问题:如何在保持代码清洁的同时,我可以通过Python在Java中执行常规操作。

9 个解决方案

#1


46  

In python, you wouldn't normally do what you are trying to do. But, the below code will do it:

在python中,你通常不会做你想做的事情。但是,以下代码将执行此操作:

strs = ["" for x in range(size)]

#2


14  

In Python, the tendency is usually that one would use a non-fixed size list (that is to say items can be appended/removed to it dynamically). If you followed this, there would be no need to allocate a fixed-size collection ahead of time and fill it in with empty values. Rather, as you get or create strings, you simply add them to the list. When it comes time to remove values, you simply remove the appropriate value from the string. I would imagine you can probably use this technique for this. For example (in Python 2.x syntax):

在Python中,通常倾向于使用非固定大小的列表(也就是说可以动态地将项目附加/移除)。如果您遵循此操作,则不需要提前分配固定大小的集合并使用空值填充它。相反,当您获取或创建字符串时,只需将它们添加到列表中即可。当需要删除值时,只需从字符串中删除适当的值即可。我想你可能会使用这种技术。例如(在Python 2.x语法中):

>>> temp_list = []
>>> print temp_list
[]
>>> 
>>> temp_list.append("one")
>>> temp_list.append("two")
>>> print temp_list
['one', 'two']
>>> 
>>> temp_list.append("three")
>>> print temp_list
['one', 'two', 'three']
>>> 

Of course, some situations might call for something more specific. In your case, a good idea may be to use a deque. Check out the post here: Python, forcing a list to a fixed size. With this, you can create a deque which has a fixed size. If a new value is appended to the end, the first element (head of the deque) is removed and the new item is appended onto the deque. This may work for what you need, but I don't believe this is considered the "norm" for Python.

当然,某些情况可能需要更具体的内容。在你的情况下,一个好主意可能是使用双端队列。看看这里的帖子:Python,强制列表固定大小。这样,您就可以创建一个具有固定大小的双端队列。如果将新值附加到末尾,则会删除第一个元素(双端队列的头部),并将新项目附加到双端队列。这可能适用于您所需要的,但我不认为这被认为是Python的“标准”。

#3


6  

The simple answer is, "You don't." At the point where you need something to be of fixed length, you're either stuck on old habits or writing for a very specific problem with its own unique set of constraints.

简单的答案是,“你没有。”在你需要固定长度的东西时,你要么坚持旧习惯,要么用一套独特的约束来写一个非常具体的问题。

#4


1  

Are you trying to do something like this?

你想做这样的事吗?

>>> strs = [s.strip('\(\)') for s in ['some\\', '(list)', 'of', 'strings']]
>>> strs 
['some', 'list', 'of', 'strings']

#5


1  

But what is a reason to use fixed size? There is no actual need in python to use fixed size arrays(lists) so you always have ability to increase it's size using append, extend or decrease using pop, or at least you can use slicing.

但是使用固定大小的原因是什么? python中没有实际需要使用固定大小的数组(列表),所以你总是能够使用pop追加,扩展或减少来增加它的大小,或者至少你可以使用切片。

x = [''  for x in xrange(10)]

#6


1  

The best and most convenient method for creating a string array in python is with the help of NumPy library.

在python中创建字符串数组的最佳和最方便的方法是在NumPy库的帮助下。

Example:

例:

import numpy as np
arr = np.chararray((rows, columns))

This will create an array having all the entries as empty strings. You can then initialize the array using either indexing or slicing.

这将创建一个数组,其中所有条目都为空字符串。然后,您可以使用索引或切片初始化数组。

#7


0  

The error message says it all: strs[sum-1] is a tuple, not a string. If you show more of your code someone will probably be able to help you. Without that we can only guess.

错误消息说明了一切:strs [sum-1]是一个元组,而不是一个字符串。如果您显示更多代码,某人可能会帮助您。没有它我们只能猜测。

#8


0  

Sometimes I need a empty char array. You cannot do "np.empty(size)" because error will be reported if you fill in char later. Then I usually do something quite clumsy but it is still one way to do it:

有时我需要一个空的char数组。您不能执行“np.empty(size)”,因为如果稍后填写char,将报告错误。然后我经常做一些非常笨拙的事情,但它仍然是一种方法:

# Suppose you want a size N char array
charlist = [' ']*N # other preset character is fine as well, like 'x'
chararray = np.array(charlist)
# Then you change the content of the array
chararray[somecondition1] = 'a'
chararray[somecondition2] = 'b'

The bad part of this is that your array has default values (if you forget to change them).

不好的一点是你的数组有默认值(如果忘记更改它们)。

#9


0  

def _remove_regex(input_text, regex_pattern):
    findregs = re.finditer(regex_pattern, input_text) 
    for i in findregs: 
        input_text = re.sub(i.group().strip(), '', input_text)
    return input_text

regex_pattern = r"\buntil\b|\bcan\b|\bboat\b"
_remove_regex("row and row and row your boat until you can row no more", regex_pattern)

\w means that it matches word characters, a|b means match either a or b, \b represents a word boundary

\ w表示它匹配单词字符,a | b表示匹配a或b,\ b表示单词边界

#1


46  

In python, you wouldn't normally do what you are trying to do. But, the below code will do it:

在python中,你通常不会做你想做的事情。但是,以下代码将执行此操作:

strs = ["" for x in range(size)]

#2


14  

In Python, the tendency is usually that one would use a non-fixed size list (that is to say items can be appended/removed to it dynamically). If you followed this, there would be no need to allocate a fixed-size collection ahead of time and fill it in with empty values. Rather, as you get or create strings, you simply add them to the list. When it comes time to remove values, you simply remove the appropriate value from the string. I would imagine you can probably use this technique for this. For example (in Python 2.x syntax):

在Python中,通常倾向于使用非固定大小的列表(也就是说可以动态地将项目附加/移除)。如果您遵循此操作,则不需要提前分配固定大小的集合并使用空值填充它。相反,当您获取或创建字符串时,只需将它们添加到列表中即可。当需要删除值时,只需从字符串中删除适当的值即可。我想你可能会使用这种技术。例如(在Python 2.x语法中):

>>> temp_list = []
>>> print temp_list
[]
>>> 
>>> temp_list.append("one")
>>> temp_list.append("two")
>>> print temp_list
['one', 'two']
>>> 
>>> temp_list.append("three")
>>> print temp_list
['one', 'two', 'three']
>>> 

Of course, some situations might call for something more specific. In your case, a good idea may be to use a deque. Check out the post here: Python, forcing a list to a fixed size. With this, you can create a deque which has a fixed size. If a new value is appended to the end, the first element (head of the deque) is removed and the new item is appended onto the deque. This may work for what you need, but I don't believe this is considered the "norm" for Python.

当然,某些情况可能需要更具体的内容。在你的情况下,一个好主意可能是使用双端队列。看看这里的帖子:Python,强制列表固定大小。这样,您就可以创建一个具有固定大小的双端队列。如果将新值附加到末尾,则会删除第一个元素(双端队列的头部),并将新项目附加到双端队列。这可能适用于您所需要的,但我不认为这被认为是Python的“标准”。

#3


6  

The simple answer is, "You don't." At the point where you need something to be of fixed length, you're either stuck on old habits or writing for a very specific problem with its own unique set of constraints.

简单的答案是,“你没有。”在你需要固定长度的东西时,你要么坚持旧习惯,要么用一套独特的约束来写一个非常具体的问题。

#4


1  

Are you trying to do something like this?

你想做这样的事吗?

>>> strs = [s.strip('\(\)') for s in ['some\\', '(list)', 'of', 'strings']]
>>> strs 
['some', 'list', 'of', 'strings']

#5


1  

But what is a reason to use fixed size? There is no actual need in python to use fixed size arrays(lists) so you always have ability to increase it's size using append, extend or decrease using pop, or at least you can use slicing.

但是使用固定大小的原因是什么? python中没有实际需要使用固定大小的数组(列表),所以你总是能够使用pop追加,扩展或减少来增加它的大小,或者至少你可以使用切片。

x = [''  for x in xrange(10)]

#6


1  

The best and most convenient method for creating a string array in python is with the help of NumPy library.

在python中创建字符串数组的最佳和最方便的方法是在NumPy库的帮助下。

Example:

例:

import numpy as np
arr = np.chararray((rows, columns))

This will create an array having all the entries as empty strings. You can then initialize the array using either indexing or slicing.

这将创建一个数组,其中所有条目都为空字符串。然后,您可以使用索引或切片初始化数组。

#7


0  

The error message says it all: strs[sum-1] is a tuple, not a string. If you show more of your code someone will probably be able to help you. Without that we can only guess.

错误消息说明了一切:strs [sum-1]是一个元组,而不是一个字符串。如果您显示更多代码,某人可能会帮助您。没有它我们只能猜测。

#8


0  

Sometimes I need a empty char array. You cannot do "np.empty(size)" because error will be reported if you fill in char later. Then I usually do something quite clumsy but it is still one way to do it:

有时我需要一个空的char数组。您不能执行“np.empty(size)”,因为如果稍后填写char,将报告错误。然后我经常做一些非常笨拙的事情,但它仍然是一种方法:

# Suppose you want a size N char array
charlist = [' ']*N # other preset character is fine as well, like 'x'
chararray = np.array(charlist)
# Then you change the content of the array
chararray[somecondition1] = 'a'
chararray[somecondition2] = 'b'

The bad part of this is that your array has default values (if you forget to change them).

不好的一点是你的数组有默认值(如果忘记更改它们)。

#9


0  

def _remove_regex(input_text, regex_pattern):
    findregs = re.finditer(regex_pattern, input_text) 
    for i in findregs: 
        input_text = re.sub(i.group().strip(), '', input_text)
    return input_text

regex_pattern = r"\buntil\b|\bcan\b|\bboat\b"
_remove_regex("row and row and row your boat until you can row no more", regex_pattern)

\w means that it matches word characters, a|b means match either a or b, \b represents a word boundary

\ w表示它匹配单词字符,a | b表示匹配a或b,\ b表示单词边界