Питон создать массив строк

Создание строкового массива – какой самый питонический путь?

Состав задачи, заданный целочисленным числом N. Обивенное начальное строковое значение S. Как создать массив n экземпляров S в Python? # Ввод, вывод: [”, ”, ”, ”, ”] Способ 1: Умножение списка Python не имеет встроенного типа массива. Эквивалент массива … Создание строкового массива – какой самый питонический путь? Подробнее “

Постановка проблемы

Как создать массив N копии S в Python?

# Input: n = 5 s = '' # Output: ['', '', '', '', '']

Метод 1: умножение списка

Python не имеет встроенного типа массива. Эквивалент массива в Java – это список в Python. Итак, мы немного изменим формулировку проблем, чтобы создать список.

Самый питонический способ создать строковый массив в Python String s и размер N это использовать умножение списка Звездочный оператор В выражении [s] * n Отказ

# Method 1: List Multiplication a = [s] * n print(a) # ['', '', '', '', '']

Фон : Введение в Звездочный оператор в Python

Метод 2: для цикла

Канонический подход состоит в том, чтобы создать пустой список и итеративно добавить одно и то же значение строки в существующий список в LOOP. Вы можете использовать стандартную функцию Python Standard.Append (Element).

# Method 2: For Loop a = [] for i in range(n): a.append(s) print(a) # ['', '', '', '', '']

Фон : Python Poops

Читайте также:  Авторизация java spring boot

Способ 3: Понимание списка

Понимание списка Является кратным способом создания нового списка в одной строке. Понимание списка является компактным способом создания списков. Простая формула – [Выражение + контекст] Отказ

  • Выражение : Что делать с элементом каждого списка?
  • Контекст : Какие элементы для выбора? Контекст состоит из произвольного числа для и, если утверждения.
# Method 3: List Comprehension a = [s for _ in range(n)] print(a) # ['', '', '', '', '']

Фон : Введение в список в списке

Метод 4: Создание Numpy Array

Numpy – стандартная библиотека Python для численных вычислений. Ближайшая вещь к массиву Java в Python является множественным массивом. Вы можете создать Numpy Array из любого списка Python, передавая список в np.array () конструктор.

# Method 4: NumPy import numpy as np a = np.array([s for _ in range(n)]) print(a) # ['' '' '' '' '']

Фон : Numpy – все, что вам нужно знать, чтобы получить Начал

Обсуждение

Тип данных строки в Python неизменен. Это означает, что вы не можете изменить строку после его создания. Это в отличие от Java, где вы можете изменить строку после его создания. Поэтому часто не имеет смысла инициализировать массив с некоторыми строками по умолчанию, потому что эти строки не могут быть изменены позже. Единственное, что вы можете сделать, это перезаписать строки в списке. Но если вы это делаете, добавив фиктивное значение, не имеет большого смысла в первую очередь.

Фоновый список видео

Куда пойти отсюда?

Достаточно теории, давайте познакомимся!

Чтобы стать успешным в кодировке, вам нужно выйти туда и решать реальные проблемы для реальных людей. Вот как вы можете легко стать шестифункциональным тренером. И вот как вы польские навыки, которые вам действительно нужны на практике. В конце концов, что такое использование теории обучения, что никто никогда не нуждается?

Практические проекты – это то, как вы обостряете вашу пилу в кодировке!

Вы хотите стать мастером кода, сосредоточившись на практических кодовых проектах, которые фактически зарабатывают вам деньги и решают проблемы для людей?

Затем станьте питоном независимым разработчиком! Это лучший способ приближения к задаче улучшения ваших навыков Python – даже если вы являетесь полным новичком.

Присоединяйтесь к моему бесплатным вебинаре «Как создать свой навык высокого дохода Python» и посмотреть, как я вырос на моем кодированном бизнесе в Интернете и как вы можете, слишком от комфорта вашего собственного дома.

Присоединяйтесь к свободному вебинару сейчас!

Работая в качестве исследователя в распределенных системах, доктор Кристиан Майер нашел свою любовь к учению студентов компьютерных наук.

Чтобы помочь студентам достичь более высоких уровней успеха Python, он основал сайт программирования образования Finxter.com Отказ Он автор популярной книги программирования Python одноклассники (Nostarch 2020), Coauthor of Кофе-брейк Python Серия самооставленных книг, энтузиаста компьютерных наук, Фрилансера и владелец одного из лучших 10 крупнейших Питон блоги по всему миру.

Его страсти пишут, чтение и кодирование. Но его величайшая страсть состоит в том, чтобы служить стремлению кодер через Finxter и помогать им повысить свои навыки. Вы можете присоединиться к его бесплатной академии электронной почты здесь.

Читайте ещё по теме:

Источник

How to create an array of strings in Python

Feature image for the article about how to create an array of strings in Python

Looking for a way to create and array of strings in Python? You came to the right place. This hands-on article explains several ways of how to create an array of strings in Python. It includes example code snippets to demonstrate how to loop over the array elements as well.

Background

A few weeks ago I was helping someone write a Python script to automate their work-flow. At one point we needed to create a string array. Since it was a while since I last coded in Python, I didn’t have the syntax memorized on how to create an array of strings. What to do? A quick web search with your search engine of choice of course. Unfortunately, the top search hits did not yield the results we were looking for. Hence this article; a quick reference on how to create an array of strings in Python. Handy for myself and hopefully for others as well.

What do you need

To follow along with the presented examples, you just need a PC with the Python interpreter installed. Since the Python interpreter runs on pretty much all operating systems, you can use Windows, macOS or Linux throughout this article. Because this blog primarily focuses on Linux, that’s what I’ll use. My trusty openSUSE Tumbleweed machine to be exact. Curious about trying out openSUSE Tumbleweed? This article gets you started:

All popular Linux distributions come with Python installed. So theoretically, you just need a text editor for writing your Python script. I personally prefer a bit of a beefier development environment: the PyCharm IDE from JetBrains. They offer a community edition, which you can use free or charge. To install the PyCharm Community edition, I recommend its Flatpak edition as explained in this article:

We’ll need a Python script for testing out the presented code snippets. Here’s one to get you started. Save it in a file called stringarrays.py :

#!/usr/bin/env python3 def main(): # TODO Enter code here.. pass if __name__ == "__main__": main()

To try out a code snippet, replace the pass line with the code snippet and then run your Python script.

Arrays in Python

First things first: What is an array? The following list sums it up:

  • An array is a list of variables of the same data type.
  • Array elements are accessed with a zero-based index.
  • You can dynamically add, remove and swap array elements.

If you know your way around a spreadsheet, you can think of an array as a one-column spreadsheet. The name of the column is the name of the array itself. Likewise, the row number is the index of an array element. You just need to keep in mind that an array index starts at 0 and not at 1 .

Time for an example. Let’s say you have a bunch of numbers ( 1000 , 1500 , 1877 and 496 ) that you want to store in an array. One way of declaring and initializing an array variable that holds these values:

# Create an array with 4 numbers my_numbers = [1000, 1500, 1877, 496]

Alternatively, you can construct the array dynamically:

# Create an empty array my_numbers = [] # Add array elements one at a time my_numbers.append(1000) my_numbers.append(1500) my_numbers.append(1877) my_numbers.append(496)

To access the element at a specific index in the array, you use square brackets. Example:

# Read the value at index 1 my_value = my_numbers[1] # Print the value print(my_value)

This prints out the value 1500 .

Terminal screenshot that shows the output of a Python script that prints a numeric array element.

Strings in Python

A string in Python is basically a variable that stores text. You surround your text by either single quotes or double quotes. Which one doesn’t really matter. It’s just a way of telling Python that the value is text and not numerical. For example:

# Create and initialize a string variable my_string = 'Just some random text.' # Print the value print(my_string)

Terminal screenshot showing the output of a Python script that prints the value of a string.

Since we already covered arrays in the previous section, you can also understand strings like this: A string is nothing more than an array of characters. So each array element holds a character of the string. To print the 4th character of the previous string:

# Read the character at index 3 my_value = my_string[3] # Print the character print(my_value)

This prints out the character t . So the last letter of the word Just that we stored in string variable my_string .

Screenshot that shows the output of a Python script that prints a character array element.

Create an array of strings in Python

Now that we know about strings and arrays in Python, we simply combine both concepts to create and array of strings. For example to store different pets. To declare and initialize an array of strings in Python, you could use:

# Create an array with pets my_pets = ['Dog', 'Cat', 'Bunny', 'Fish']

Just like we saw before, you can also construct the array one element at a time:

# Create an empty array my_pets = [] # Add array elements one at a time my_pets.append('Dog') my_pets.append('Cat') my_pets.append('Bunny') my_pets.append('Fish')

Since it’s an array, you can access each element using square brackets and specifying its zero based index. To read and print the 3rd pet in the string array, we use index 2 :

# Read the value at index 2 my_pet = my_pets[2] # Print the value print(my_pet)

Output of a Python script that creates and array of strings and prints one element at a specific array index onto the screen.

In case you don’t know which pet to get in real life, you could let Python decide for you, using its random number generator. To access the random number generator, import its module by adding this line at the top of your Python file:

We can now generate a random number between 0 and 3, which later serves as an index into our string array with pets:

my_pet_index = random.randint(0, 3)

Putting it all together to request Python to decide on a pet for us:

my_pets = ['Dog', 'Cat', 'Bunny', 'Fish'] my_pet_index = random.randint(0, 3) my_pet = my_pets[my_pet_index] print(my_pet)

In my case, it turns out Python wants me to get a Bunny :

Screenshot showing the output of a Python program that randomly selects an item from a previously created array of strings.

Loop over a string array in Python

When storing strings (or other data) in an array, you do so for a purpose in your Python program. Working with the resulting array, typically involves looping over its contents. This looping is sometimes called iterating. Several methods exists for looping over an array. The most concise one:

for pet in my_pets: print(pet)

These two lines of code pack a whole lot of functionality:

Output of a Python script that loops over each element of a string array and prints the element

  • It loops over each array element in string array my_pets .
  • The current element is stored in a variable called pet . Note that you can change this variable name to whatever you prefer.
  • Inside the loop, we print out the name of the current element.

A more verbose approach with an array indexer:

pet_index = 0 while pet_index < len(my_pets): print(my_pets[pet_index]) pet_index += 1
  • The first line declares and initializes an indexer variable pet_index . You can change this variable name to something else, if your prefer.
  • The loop repeats as long as the pet_index value is less than the total number of elements in the my_pets array.
  • Inside the loop body, we:
    • Print out the name of the array element at the current index.
    • Increment the pet_index value by one in preparation for the next loop iteration.

    Both methods for looping over an array in Python do the same. Whichever method you use is up to your own personal preference.

    Wrap up

    This article set out to explain how to create an array of strings in Python. Before diving into this topic, we first learned how about arrays and strings, independently. Afterwards, we combined what we learned and applied it to create string arrays. Afterwards, we covered looping through array elements. As an often used technique, this article would haven been incomplete without covering it.

    PragmaticLinux

    Long term Linux enthusiast, open source software developer and technical writer.

    Источник

Оцените статью