I don't know how to search the list partially.
If you want to add only the following list, for example, '.xlsx' to the new list,
How should I describe the code?
In seemed to be applied only to exact matches in the search in the list.
Thank you for your cooperation.
↓ This is all I can do, but
list=['aaa.xlsx', 'bbb.xlsx', 'ccc.csv' ]
newlist=[ ]
kensaku='aaa.xlsx'
if kensaku in list:
newlist.append(kensaku)
↓This is not enough
list=['aaa.xlsx', 'bbb.xlsx', 'ccc.csv' ]
newlist=[ ]
kensaku='.xlsx'
if kensaku in list:
newlist.append(kensaku)
How about this?
l=['aaa.xlsx', 'bbb.xlsx', 'ccc.csv' ]
newl=[ ]
kensaku='.xlsx'
if any(s.endswith(kensaku) for sinl):
newl.append(kensaku)
The By the way, If so, it will be overwritten and will no longer be available as a model name, so you should avoid it.s.endswith(kensaku)for sin l
part verifies that each element of l
ends with a kensaku
and returns a list of Boolean values (although it is actually a generator).In the above example, [True, True, False]
any
returns True
if even one element in the list of arguments is True
, so any(s.endswith(kensaku) for thinl)
as a whole, if any string in l
ends list
is the type defined by default in Python.list=['aaa.xlsx', 'bbb.xlsx', 'ccc.csv' ]
There is no convenient feature to take out a partial match for each list element, so write as follows:
list=['aaa.xlsx', 'bbb.xlsx', 'ccc.csv' ]
newlist=[ ]
kensaku='.xlsx'
For lin list:
if kensakuinl:
newlist.append(l)
You can write as follows using the inclusion notation.
list=['aaa.xlsx', 'bbb.xlsx', 'ccc.csv' ]
newlist=[l for lin list if'.xlsx'inl]
If you want to take out the extension, it's more accurate to use .endswith as Hideki wrote.
list=['aaa.xlsx', 'bbb.xlsx', 'ccc.csv' ]
newlist=[l for line list if l.endswith('.xlsx')]
© 2024 OneMinuteCode. All rights reserved.