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

后端 未结 11 1392
南旧
南旧 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:32

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

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-03 18:43

    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.

    0 讨论(0)
  • 2021-02-03 18:44
    strlist =[{}]*10
    strlist[0] = set()
    strlist[0].add("Beef")
    strlist[0].add("Fish")
    strlist[1] = {"Apple", "Banana"}
    strlist[1].add("Cherry")
    print(strlist[0])
    print(strlist[1])
    print(strlist[2])
    print("Array size:", len(strlist))
    print(strlist)
    
    0 讨论(0)
  • 2021-02-03 18:45

    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.

    x = [''  for x in xrange(10)]
    
    0 讨论(0)
提交回复
热议问题