Mainly for myself. I started Python for a competition pro, so I'll make a note of what I often forget.
Basically, specify the range at the end like ls [2: 5]. In this case, the index of ls elements of 2 or more and less than 5 is output.
ls=[0,1,2,3,4,5,6,7,8,9]
subls_1=ls[2:8]
print(subls_1)
#=> [2,3,4,5,6,7]
If you take a subarray several times, pay attention to the index. (Failed several times)
ls=[0,1,2,3,4,5,6,7,8,9]
subls_1=ls[2:8]
subls_2=ls[1:4]
print(subls_2)
#=> [3,4,5]
Either number can be omitted.
ls=[0,1,2,3,4,5,6,7,8,9]
subls_3=ls[:8]
print(subls_3)
#=> [0,1,2,3,4,5,6,7]
subls_4=ls[2:]
print(subls_4)
#=> [2,3,4,5,6,7,8,9]
You can also retrieve every two or three elements. Note the ":" when omitting numbers.
ls=[0,1,2,3,4,5,6,7,8,9]
subls_5=ls[2:8:3]
print(subls_5)
#=> [2,5]
subls_6=ls[::3]
print(subls_6)
#=> [0,3,6,9]
When outputting an array separated by spaces, prefix it with "*".
ls=[0,1,2,3,4,5,6,7,8,9]
print(ls)
#=> [0,1,2,3,4,5,6,7,8,9]
print(*ls)
#=> 0 1 2 3 4 5 6 7 8 9
When space is not required, such as when outputting characters, the arrays are combined before output. Note that this cannot be used for int types.
ls2=['a', 'b', 'c']
print(ls2)
#=> ['a', 'b', 'c']
print("".join(ls2))
#=> abc
(Addition) I was told in the comments how to use it without worrying about the type. Thank you very much.
ls=[0,1,2,3,4,5,6,7,8,9]
print(*ls, sep='')
#=> 0123456789
Recommended Posts