“Pemahaman Daftar Python” Kode Jawaban

Pemahaman Daftar Python

squares = [item * item for item in range(5)]
Ninad Pethkar

Pemahaman Daftar Python

liste range(101) = new_list = []
for i in liste:
if i%5 0: ==
if i%10 == 0:
new_list.append(i**2)
Healthy Heron

Pemahaman Daftar Python

[expression for element in source_list]
Naughty Nightingale

Pemahaman Daftar Python

l = [i for i in some_container]
Nischal Kafle

Pemahaman Daftar Python

>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
  File "<stdin>", line 1, in <module>
    [x, x**2 for x in range(6)]
               ^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> # List comprehensions can contain complex expressions and nested functions:
>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
Rubber Duck

Pemahaman Daftar Python

say something
Tholits

Pemahaman Daftar Python

 # A list comprehnsion is a for loop on a single line 
 # To create a list comprehension, swap the two lines in the for loop.

# Here we use PyBIDS to extract the relative path for each file:
for fmri in fmri_078:
    print(fmri.relpath)

# And here is the equivalent statement as a list comprehension.
# It must be enclosed in square brackets.
# It swaps the order of the lines and loses the colon and indentation
[ print(fmri.relpath) for fmri in fmri_078 ]   
Troubled Tapir

Pemahaman Daftar Python

squares = [item * item for item in range(5)]
Ninad Pethkar

Pemahaman Daftar Python

squares = [item * item for item in range(5)]
Ninad Pethkar

Pemahaman Daftar Python

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
  if "a" in x:
    newlist.append(x)

print(newlist)
SAMER SAEID

Jawaban yang mirip dengan “Pemahaman Daftar Python”

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya