I have a list of lists with strings.
words = [['gamma_ray_bursts','merger','death','throes','magnetic_flares','neutrino_antineutrino','objections','bursts','double_neutron_star','parker_instability','positrons'],
['dot','gravitational_lensing','splittings','limits','amplifications','time_delays','extracting_information','fix','distant_quasars'],
['recoil','gamma_ray_bursts','neutron_stars','jennings','possible_origins','birthplaces','disjoint','arrival_directions'],
['sn_sn','type_ii_supernovae','distances','dilution','extinction','extragalactic_distance_scale','expanding_photosphere','distance','photospheres','supernovae_sn','span_wide_range'],
['photon_pair','high_energy','gamma_ray_burst','optical_depth','absorbing_medium','implications','problem','annihilation_radiation','emergent_spectrum','limit','radiation_transfer','collimation','regions']]
- I would like to remove any elements of a list if it is a substring of another element.
- I would like the order preserved
' I have tried this loop:
for string_list in words:
for item in string_list:
for item1 in string_list:
if item in item1 and item!= item1:
string_list.remove(item)
It seems to work with smaller list of lists but outputs an error when I increase the len of the list.
ValueError Traceback (most recent call last)
<ipython-input-91-7546f608171f> in <module>
4 for item1 in string_list:
5 if item in item1 and item!= item1:
----> 6 string_list.remove(item)
ValueError: list.remove(x): x not in list
expected output:
words = [['gamma_ray_bursts','merger','death','throes','magnetic_flares','neutrino_antineutrino','objections','double_neutron_star','parker_instability','positrons'], ['dot','gravitational_lensing','splittings','limits','amplifications','time_delays','extracting_information','fix','distant_quasars'],['recoil','gamma_ray_bursts','neutron_stars','jennings','possible_origins','birthplaces','disjoint','arrival_directions'], ['sn_sn','type_ii_supernovae','distances','dilution','extinction','extragalactic_distance_scale','expanding_photosphere','photospheres','supernovae_sn','span_wide_range'],['photon_pair','high_energy','gamma_ray_burst','optical_depth','absorbing_medium','implications','problem','annihilation_radiation','emergent_spectrum','limit','radiation_transfer','collimation','regions']]
I've searched the forums, there is a very similar question and the solution works sometimes but other times it outputs an error, it's not consistent where this error occurs. The length of the list is variable. Python - Remove any element from a list of strings that is a substring of another element