I want to select a range between elements in a list, but instead of putting, for example, item 7, I put what I’m seeing in elements. The number between ‘document’ and ‘35621’ changes, I need to convert these numbers to a range (I think?)
I don’t really know how to make this.
JavaScript
x
6
1
data_input = raw_input("nEnter range: n")
2
3
my_list = ['document-452-35621', 'document-453-35621', 'document-454-35621', 'document-455-35621', 'document-456-35621', 'document-457-35621', 'document-458-35621', 'document-459-35621', 'document-460-35621']
4
5
print my_list[5:9]
6
For example, in my list I have:
JavaScript
1
12
12
1
[
2
'document-452-35621',
3
'document-453-35621',
4
'document-454-35621',
5
'document-455-35621',
6
'document-456-35621',
7
'document-457-35621',
8
'document-458-35621',
9
'document-459-35621',
10
'document-460-35621'
11
]
12
I enter in choice input : 456-460
The result would be:
JavaScript
1
8
1
[
2
'document-456-35621',
3
'document-457-35621',
4
'document-458-35621',
5
'document-459-35621',
6
'document-460-35621'
7
]
8
Advertisement
Answer
You can do it like this:
JavaScript
1
23
23
1
my_list = [
2
'document-452-35621',
3
'document-453-35621',
4
'document-454-35621',
5
'document-455-35621',
6
'document-456-35621',
7
'document-457-35621',
8
'document-458-35621',
9
'document-459-35621',
10
'document-460-35621'
11
]
12
13
data_input = input("nEnter range: n").split('-') # ['456', '460']
14
lower_bound = int(data_input[0]) # 456
15
upper_bound = int(data_input[1]) # 460
16
17
new_list = []
18
for item in my_list:
19
if lower_bound <= int(item.split('-')[1]) <= upper_bound:
20
new_list.append(item)
21
22
print(new_list)
23
Or alternatively, you can use List Comprehension and do it like this:
JavaScript
1
3
1
new_list = [item for item in my_list if lower_bound <= int(item.split('-')[1]) <= upper_bound]
2
print(new_list)
3
Output:
JavaScript
1
8
1
[
2
'document-456-35621',
3
'document-457-35621',
4
'document-458-35621',
5
'document-459-35621',
6
'document-460-35621'
7
]
8
I can see that you’re using Python 2
, so the only difference I think is with the print
and raw_input
. However, since “Python 2.7 will not be maintained past 2020,” I would encourage you to use Python 3
and above.