zinon zinon - 1 year ago 127
Python Question

Python 2.7: Keep only specific lists in a list

I'm using

python 2.7
and I have a list that contains lists.

Here is my list:

range_list=[['encoding_txt\\pirkagia_10b_192x144_15_qp_26_ON_encoder_randomaccess_B16_Filters_ON_scalable_JOURNAL2017.txt', 26, 35.1782, 136.8125, 300.788, 0.844, -3.5, '192x144'],
['encoding_txt\\pirkagia_10b_192x144_25_qp_26_ON_encoder_randomaccess_B16_Filters_ON_scalable_JOURNAL2017.txt', 26, 35.1782, 228.0208, 302.251, 0.962, -2.5, '192x144'],
['encoding_txt\\pirkagia_10b_384x288_15_qp_28_ON_encoder_randomaccess_B16_Filters_ON_scalable_JOURNAL2017.txt', 28, 35.2193, 275.4614, 1065.412, 2.167, -2, '384x288'],
['encoding_txt\\pirkagia_10b_384x288_25_qp_28_ON_encoder_randomaccess_B16_Filters_ON_scalable_JOURNAL2017.txt', 28, 35.2193, 459.1024, 1064.403, 2.771, -1, '384x288'],
['encoding_txt\\pirkagia_10b_720x576_15_qp_30_ON_encoder_randomaccess_B16_Filters_ON_scalable_JOURNAL2017.txt', 30, 35.5282, 484.3387, 3536.937, 6.679, 1.5, '720x576'],
['encoding_txt\\pirkagia_10b_720x576_25_qp_30_ON_encoder_randomaccess_B16_Filters_ON_scalable_JOURNAL2017.txt', 30, 35.5282, 807.2312, 3553.744, 6.637, 2.5, '720x576']]


I want to keep only lists that contain the string
_25_
in the first row.

For example the new list must be:

range_list1 = [['encoding_txt\\pirkagia_10b_192x144_25_qp_26_ON_encoder_randomaccess_B16_Filters_ON_scalable_JOURNAL2017.txt', 26, 35.1782, 228.0208, 302.251, 0.962, -2.5, '192x144'],
['encoding_txt\\pirkagia_10b_384x288_25_qp_28_ON_encoder_randomaccess_B16_Filters_ON_scalable_JOURNAL2017.txt', 28, 35.2193, 459.1024, 1064.403, 2.771, -1, '384x288'],
['encoding_txt\\pirkagia_10b_720x576_25_qp_30_ON_encoder_randomaccess_B16_Filters_ON_scalable_JOURNAL2017.txt', 30, 35.5282, 807.2312, 3553.744, 6.637, 2.5, '720x576']]

Answer Source

You can use a simple list comprehension:

[s for s in range_list if '_25_' in s[0]]

I have also changed the name of your list since range is a function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download