根据字符串的一部分查找元素并获取值
Find a element based on the part of a string and get the value
我有一个由
创建的文件路径
Path('filepath')
我想在文件路径中间获取一个目录名并将其附加到列表中。
选择的条件是字符串的特定部分。
我试过了
list = []
list.append(x for x in str(filepath).split(os.sep) if 'part of a sting' in x)
我试过这个但是当我只打印出来时
print(x for x in str(filepath).split(os.sep) if 'part of a sting' in x)
它给了我生成器格式而不是文件路径的一部分
<generator object function.<locals>.<genexpr> at 0x7f23c8dd0258>
这里有什么问题?
您获得了生成器对象,因为您使用的是生成器表达式而不是列表理解。您可以阅读有关生成器表达式的更多信息 here
试着写这样的东西:
path_list = [x for x in str(filepath).split(os.sep) if 'part of a sting' in x]
print(path_list)
我有一个由
创建的文件路径Path('filepath')
我想在文件路径中间获取一个目录名并将其附加到列表中。 选择的条件是字符串的特定部分。 我试过了
list = []
list.append(x for x in str(filepath).split(os.sep) if 'part of a sting' in x)
我试过这个但是当我只打印出来时
print(x for x in str(filepath).split(os.sep) if 'part of a sting' in x)
它给了我生成器格式而不是文件路径的一部分
<generator object function.<locals>.<genexpr> at 0x7f23c8dd0258>
这里有什么问题?
您获得了生成器对象,因为您使用的是生成器表达式而不是列表理解。您可以阅读有关生成器表达式的更多信息 here
试着写这样的东西:
path_list = [x for x in str(filepath).split(os.sep) if 'part of a sting' in x]
print(path_list)