List the List
A list in Python is an array of variable length, which I prefer to compare to a List in Java. The underlying implementation of an ArrayList in Java is an array, which is copied by adding () and removing () once it reaches its capacity.
Increased 1.
strings=["a"."b"."c"]
strings.append("d")
strings.insert(0."s")
print(strings)
Copy the code
Results:
['s'.'a'.'b'.'c'.'d']
Copy the code
2. Delete
Delete by index:
strings=["a"."b"."c"]
del strings[0]
print("del()".center(20."-"))
print(strings)
strings1=["a"."b"."c"]
a=strings1.pop()
print("pop()".center(20."-"))
print(a)
print(strings1)
strings2=["a"."b"."c"]
b=strings2.pop(1)
print("pop(index)".center(20."-"))
print(b)
print(strings2)
Copy the code
The results of
-------del() -- -- -- -- -- -- -- -'b'.'c']
-------pop()--------
c
['a'.'b']
-----pop(index)-----
b
['a'.'c']
Copy the code
Pop () if you want to delete the returned value, del() otherwise.
According to the value delete
strings=["a"."b"."c"]
strings.remove("c")
print(strings)
Copy the code
['a', 'b']
Copy the code
3. Change
If you know the index of the value that needs to be modified in the list:
strings=["a"."b"."c"]
strings[0] ="s"
print(strings)
Copy the code
['s'.'b'.'c']
Copy the code
If the value is known:
strings=["a"."b"."c"]
strings[strings.index("b")] ="s"
print(strings)
Copy the code
['a'.'s'.'c']
Copy the code
4. Check
slice
strings=["a"."d"."s"."h"]
print(strings[1:3])
Copy the code
The results of
['d'.'s']
Copy the code
The sorting
strings=["a"."d"."s"."h"]
Sort by first letter
strings.sort()
print("sort()".center(20."-"))
print(strings)
strings1=["a"."d"."s"."h"]
Sort by reverse alphabetic
strings1.sort(reverse=True)
print("sort(reverse)".center(20."-"))
print(strings1)
strings2=["a"."d"."s"."h"]
# temporary sort by first letter, do not change the list order
print("sorted".center(20."-"))
print(sorted(strings2))
print(strings2)
Copy the code
The results of
-------sort()-------
['a'.'d'.'h'.'s']
---sort(reverse)----
['s'.'h'.'d'.'a'-- -- -- -- -- -- --sorted() -- -- -- -- -- -- -'a'.'d'.'h'.'s']
['a'.'d'.'s'.'h']
Copy the code
traverse
Note that Python determines the relationship between line code and uplink code based on indentation;
strings=["a"."b"."c"."d"]
for string in strings:
print(string.title())
print("ssr")
Copy the code
A
B
C
D
ssr
Copy the code
Clever use of range()
# Print out 1-100
for num in range(1.101) :print(num)
Print an even number from 1 to 100
print(list(range(0.101.2)))
Take the sum of even numbers in 100
print(sum(list(range(0.101.2))))
Copy the code
The results of
2550
Copy the code
I have to say that if I were Java I would probably go through it and decide what’s divisible by 2 and put it in a variable. Python is very convenient.
Parse the list using for
squares1=[1.3.5.7.9]
squares2=[v**3 for v in squares1]
print(squares2)
squares3=[value**2 for value in range(1.11)]
print(squares3)
Copy the code
Results:
[1.27.125.343.729]
[1.4.9.16.25.36.49.64.81.100]
Copy the code