What is the best way to create a string array in python?

后端 未结 11 1387
南旧
南旧 2021-02-03 17:45

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

11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-03 18:42

    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):

    >>> 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.

提交回复
热议问题