Arrays
Listen
# Creating a list my_list = [] my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # List of different data types mixed_list = [1, "hello", 3.14, True] # Accessing elements print(my_list[0]) # Output: 1 print(my_list[-1]) # Output: 5 # Append to the end my_list.append(6) # Insert at a specific position my_list.insert(2, 10) # Find an element in an array index=my_list.find(element) # Remove by value my_list.remove(10) # Remove by index removed_element = my_list.pop(2) # Length of the list print(len(my_list)) # Slicing [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # sequence[start:stop:step] print(my_list[1:4]) # Output: [1, 2, 3] print(my_list[5:]) # Output: [5, 6, 7, 8, 9] print(my_list[:5]) # Output: [0, 1, 2, 3, 4] print(my_list[::2]) # Output: [0, 2, 4, 6, 8] print(my_list[-4:]) # Output: [6, 7, 8, 9] print(my_list[:-4]) # Output: [0, 1, 2, 3, 4, 5] print(my_list[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] print(my_list[8:2:-2]) # Output: [8, 6, 4] print(my_list[1:8:2]) # Output: [1, 3, 5, 7] print(my_list[-2:-7:-1]) # Output: [8, 7, 6, 5, 4] # Reversing a list my_list.reverse() # Sorting a list my_list.sort()
Permutation und Kombination
import itertools # Example list data = [1, 2, 3] # Generating permutations of the entire list perms = list(itertools.permutations(data)) print(perms) # Output: [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] # Generating permutations of length 2 perms_length_2 = list(itertools.permutations(data, 2)) print(perms_length_2) # Output: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] combinations(iterable, r) #order does not matter
Permutationen manuell generieren
Sie können Permutationen auch manuell mithilfe der Rekursion generieren. Hier ist eine einfache Implementierung:
def permute(arr): result = [] # Base case: if the list is empty, return an empty list if len(arr) == 0: return [[]] # Recursive case for i in range(len(arr)): elem = arr[i] rest = arr[:i] + arr[i+1:] for p in permute(rest): result.append([elem] + p) return result
Stapel
(Liste kann als Stapel verwendet werden)
st=[] st.append() st.pop() top_element = stack[-1]
Tipps
1) Streifen:
Es wird verwendet, um führende und nachfolgende Leerzeichen (oder andere angegebene Zeichen) aus einer Zeichenfolge zu entfernen
#EX. (1,2) to 1,2 s.strip('()')
2) Verwenden Sie kein normales Wörterbuch
from collections import defaultdict dictionary=defaultdict(int)
3) Wichtige Prüfung und Umrechnung
s.isdigit() s.isalpha() s.isalnum() s.islower() s.isupper() s.lower() s.upper()
4) Nicht trivial
round(number, decimal_digits) ord(each)-ord('a')+1 # value of an alphabet #/ (Floating-Point Division) #// (Floor Division) maxim = float('-inf') minim = float('inf') unique_lengths.sort(reverse=True) s.count('x') list1 = [1, 2, 3] iterable = [4, 5, 6] list1.extend(iterable) position.replace('(', '').replace(')', '') expression = "2 + 3 * 4" result = eval(expression) print(result) #Determinant import numpy as arr=[[1,2,3],[3,4,5],[5,6,7]] print(np.linalg.det(np.array(arr)))
Sortiert
my_list = [3, 1, 4, 1, 5] sorted_list = sorted(my_list) my_tuple = (3, 1, 4, 1, 5) sorted_list = sorted(my_tuple) my_dict = {'apple': 3, 'banana': 1, 'cherry': 2} sorted_keys = sorted(my_dict) my_list = [3, 1, 4, 1, 5] sorted_list = sorted(my_list, reverse=True)
Aufzählen
my_list = ['a', 'b', 'c'] for index, value in enumerate(my_list): print(index, value)
Übergeben Sie die Objektreferenz
Unveränderliche Typen (wie Ganzzahlen, Strings, Tupel):
def modify_immutable(x): x = 10 # Rebinding the local variable to a new object print("Inside function:", x) a = 5 modify_immutable(a) #prints 10 print("Outside function:", a) #prints 5
Veränderbare Typen (wie Listen, Wörterbücher, Mengen):
def modify_mutable(lst): lst.append(4) # Modifying the original list object print("Inside function:", lst) my_list = [1, 2, 3] modify_mutable(my_list) # [1,2,3] print("Outside function:", my_list) # [1,2,3,4]
Numpy-Arrays (für numerische Operationen)
import numpy as np # Creating a 1D array arr_1d = np.array([1, 2, 3, 4, 5]) # Creating a 2D array arr_2d = np.array([[1, 2, 3], [4, 5, 6]]) # Creating an array filled with zeros zeros = np.zeros((3, 4)) # Creating an array filled with ones ones = np.ones((2, 3)) # Creating an array with a range of values range_arr = np.arange(0, 10, 2) # Creating an array with evenly spaced values linspace_arr = np.linspace(0, 1, 5) # Creating an identity matrix identity_matrix = np.eye(3) # Shape of the array shape = arr_2d.shape # Output: (2, 3) # Size of the array (total number of elements) size = arr_2d.size # Output: 6 # Element-wise addition arr_add = arr_1d + 5 # Output: array([6, 7, 8, 9, 10]) # Element-wise subtraction arr_sub = arr_1d - 2 # Output: array([ -1, 0, 1, 2, 3]) # Element-wise multiplication arr_mul = arr_1d * 2 # Output: array([ 2, 4, 6, 8, 10]) # Element-wise division arr_div = arr_1d / 2 # Output: array([0.5, 1. , 1.5, 2. , 2.5]) # Sum total_sum = np.sum(arr_2d) # Output: 21 # Mean mean_value = np.mean(arr_2d) # Output: 3.5 # Standard deviation std_dev = np.std(arr_2d) # Output: 1.707825127659933 # Maximum and minimum max_value = np.max(arr_2d) # Output: 6 min_value = np.min(arr_2d) # Output: 1 # Reshaping reshaped_arr = arr_1d.reshape((5, 1)) # Flattening flattened_arr = arr_2d.flatten() # Transposing transposed_arr = arr_2d.T # Indexing element = arr_2d[1, 2] # Output: 6 # Slicing subarray = arr_2d[0:2, 1:3] # Output: array([[2, 3], [5, 6]])
Astyp
Es handelt sich um eine Funktion in NumPy, die zum Konvertieren eines Numpy-Arrays in einen anderen Datentyp verwendet wird.
# Datatypes: np.int32,np.float32,np.float64,np.str_ import numpy as np # Create an integer array int_array = np.array([1, 2, 3, 4, 5], dtype=np.int32) # Convert to float float_array = int_array.astype(np.float32) print("Original array:", int_array) print("Converted array:", float_array)
Umformen
Es ist ein leistungsstarkes Tool zum Ändern der Form eines Arrays, ohne seine Daten zu ändern
import numpy as np # Create a 1D array array = np.arange(12) # Reshape to a 2D array (3 rows x 4 columns) reshaped_array = array.reshape((3, 4))
Matplotlib
import numpy as np import matplotlib.pyplot as plt # Create a random 2D array data = np.random.rand(10, 10) # Create a figure with a specific size and resolution plt.figure(figsize=(8, 6), dpi=100) # Display the 2D array as an image plt.imshow(data, cmap='viridis', interpolation='nearest') # Add a color bar to show the scale of values plt.colorbar() # Show the plot plt.show()
Wörterbuch
# Creating an empty dictionary # Maintains ascending order like map in cpp my_dict = {} # Creating a dictionary with initial values my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'} # Creating a dictionary using the dict() function my_dict = dict(name='Alice', age=25, city='New York') # Accessing a value by key name = my_dict['name'] # Output: 'Alice' # Using the get() method to access a value age = my_dict.get('age') # Output: 25 country = my_dict.get('country') # Output: None # Adding a new key-value pair my_dict['email'] = 'alice@example.com' # Updating an existing value my_dict['age'] = 26 # Removing a key-value pair using pop() age = my_dict.pop('age') # Removes 'age' and returns its value # Getting all keys in the dictionary keys = my_dict.keys() # Output: dict_keys(['name', 'email']) # Getting all values in the dictionary values = my_dict.values() # Output: dict_values(['Alice', 'alice@example.com']) # Iterating over keys for key in my_dict: print(key) # Iterating over values for value in my_dict.values(): print(value) # Iterating over key-value pairs for key, value in my_dict.items(): print(f"{key}: {value}")
Standarddikt
from collections import defaultdict d = defaultdict(int) # Initializes 0 to non-existent keys d['apple'] += 1 d['banana'] += 2
Satz
# Creating an empty set my_set = set() # Creating a set with initial values my_set = {1, 2, 3, 4, 5} # Creating a set from a list my_list = [1, 2, 3, 4, 5] my_set = set(my_list) # Creating a set from a string my_set = set('hello') # Output: {'e', 'h', 'l', 'o'} # Adding an element to a set my_set.add(6) # my_set becomes {1, 2, 3, 4, 5, 6} # Removing an element from a set (raises KeyError if not found) my_set.remove(3) # my_set becomes {1, 2, 4, 5, 6} # Removing and returning an arbitrary element from the set element = my_set.pop() # Returns and removes an arbitrary element
Zeichenfolge
# Single quotes str1 = 'Hello' # Double quotes str2 = "World" # Triple quotes for multi-line strings str3 = '''This is a multi-line string.''' # Raw strings (ignores escape sequences) raw_str = r'C:\Users\Name' str1 = 'Hello' # Accessing a single character char = str1[1] # 'e' # Accessing a substring (slicing) substring = str1[1:4] # 'ell' # Negative indexing last_char = str1[-1] # 'o' # Using + operator concatenated = 'Hello' + ' ' + 'World' # 'Hello World' # Using join method words = ['Hello', 'World'] concatenated = ' '.join(words) # 'Hello World' name = 'Alice' age = 25 # String formatting formatted_str = f'My name is {name} and I am {age} years old.' # Convert to uppercase upper_str = str1.upper() # 'HELLO WORLD' # Convert to lowercase lower_str = str1.lower() # 'hello world' # Convert to capitalize capital_str = str1.capitalize() # 'Hello world' str1 = ' Hello World ' # Remove leading and trailing whitespace trimmed = str1.strip() # 'Hello World' str1 = 'Hello World Python' # Split the string into a list of substrings split_list = str1.split() # ['Hello', 'World', 'Python'] # Split the string with a specific delimiter split_list = str1.split(' ') # ['Hello', 'World', 'Python'] # Join a list of strings into a single string joined_str = ' '.join(split_list) # 'Hello World Python' str1 = 'Hello World' # Find the position of a substring pos = str1.find('World') # 6 str1 = 'Hello123' # Check if all characters are alphanumeric is_alnum = str1.isalnum() # True # Check if all characters are alphabetic is_alpha = str1.isalpha() # False # Check if all characters are digits is_digit = str1.isdigit() # False # Check if all characters are lowercase is_lower = str1.islower() # False # Check if all characters are uppercase is_upper = str1.isupper() # False
Bleiben Sie in Verbindung!
Wenn Ihnen dieser Beitrag gefallen hat, vergessen Sie nicht, mir in den sozialen Medien zu folgen, um weitere Updates und Einblicke zu erhalten:
Twitter: madhavganesan
Instagram: madhavganesan
LinkedIn: madhavganesan
Das obige ist der detaillierte Inhalt vonPython-Codeausschnitte. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Um die Effizienz des Lernens von Python in einer begrenzten Zeit zu maximieren, können Sie Pythons DateTime-, Zeit- und Zeitplanmodule verwenden. 1. Das DateTime -Modul wird verwendet, um die Lernzeit aufzuzeichnen und zu planen. 2. Das Zeitmodul hilft, die Studie zu setzen und Zeit zu ruhen. 3. Das Zeitplanmodul arrangiert automatisch wöchentliche Lernaufgaben.

Python zeichnet sich in Gaming und GUI -Entwicklung aus. 1) Spielentwicklung verwendet Pygame, die Zeichnungen, Audio- und andere Funktionen bereitstellt, die für die Erstellung von 2D -Spielen geeignet sind. 2) Die GUI -Entwicklung kann Tkinter oder Pyqt auswählen. Tkinter ist einfach und einfach zu bedienen. PYQT hat reichhaltige Funktionen und ist für die berufliche Entwicklung geeignet.

Python eignet sich für Datenwissenschafts-, Webentwicklungs- und Automatisierungsaufgaben, während C für Systemprogrammierung, Spieleentwicklung und eingebettete Systeme geeignet ist. Python ist bekannt für seine Einfachheit und sein starkes Ökosystem, während C für seine hohen Leistung und die zugrunde liegenden Kontrollfunktionen bekannt ist.

Sie können grundlegende Programmierkonzepte und Fähigkeiten von Python innerhalb von 2 Stunden lernen. 1. Lernen Sie Variablen und Datentypen, 2. Master Control Flow (bedingte Anweisungen und Schleifen), 3.. Verstehen Sie die Definition und Verwendung von Funktionen, 4. Beginnen Sie schnell mit der Python -Programmierung durch einfache Beispiele und Code -Snippets.

Python wird in den Bereichen Webentwicklung, Datenwissenschaft, maschinelles Lernen, Automatisierung und Skripten häufig verwendet. 1) In der Webentwicklung vereinfachen Django und Flask Frameworks den Entwicklungsprozess. 2) In den Bereichen Datenwissenschaft und maschinelles Lernen bieten Numpy-, Pandas-, Scikit-Learn- und TensorFlow-Bibliotheken eine starke Unterstützung. 3) In Bezug auf Automatisierung und Skript ist Python für Aufgaben wie automatisiertes Test und Systemmanagement geeignet.

Sie können die Grundlagen von Python innerhalb von zwei Stunden lernen. 1. Lernen Sie Variablen und Datentypen, 2. Master -Steuerungsstrukturen wie wenn Aussagen und Schleifen, 3. Verstehen Sie die Definition und Verwendung von Funktionen. Diese werden Ihnen helfen, einfache Python -Programme zu schreiben.

Wie lehre ich innerhalb von 10 Stunden die Grundlagen für Computer -Anfänger für Programmierungen? Wenn Sie nur 10 Stunden Zeit haben, um Computer -Anfänger zu unterrichten, was Sie mit Programmierkenntnissen unterrichten möchten, was würden Sie dann beibringen ...

Wie kann man nicht erkannt werden, wenn Sie Fiddlereverywhere für Man-in-the-Middle-Lesungen verwenden, wenn Sie FiddLereverywhere verwenden ...


Heiße KI -Werkzeuge

Undresser.AI Undress
KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover
Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool
Ausziehbilder kostenlos

Clothoff.io
KI-Kleiderentferner

AI Hentai Generator
Erstellen Sie kostenlos Ai Hentai.

Heißer Artikel

Heiße Werkzeuge

Dreamweaver CS6
Visuelle Webentwicklungstools

Sicherer Prüfungsbrowser
Safe Exam Browser ist eine sichere Browserumgebung für die sichere Teilnahme an Online-Prüfungen. Diese Software verwandelt jeden Computer in einen sicheren Arbeitsplatz. Es kontrolliert den Zugriff auf alle Dienstprogramme und verhindert, dass Schüler nicht autorisierte Ressourcen nutzen.

SublimeText3 Linux neue Version
SublimeText3 Linux neueste Version

MantisBT
Mantis ist ein einfach zu implementierendes webbasiertes Tool zur Fehlerverfolgung, das die Fehlerverfolgung von Produkten unterstützen soll. Es erfordert PHP, MySQL und einen Webserver. Schauen Sie sich unsere Demo- und Hosting-Services an.

WebStorm-Mac-Version
Nützliche JavaScript-Entwicklungstools