英文:
How can I filter folder directories by a certain variable using Python?
问题
I understand your request. Here is the translated code part:
我正在尝试在目录内随机选择一个文件夹,可能使用 `random.choice()`(或其他方式)。但实际上它并不是完全随机的。首先,它必须根据条件或变量对目录内的文件夹进行筛选,然后从该列表中随机选择一个文件夹。
示例:
目录内的文件夹列表如下:
`peter_folder1`, `peter_folder2`, `peter_folder3`, `denise_folder1`, `denise_folder2`, `mark_folder1`, `mark_folder2`
我想要从 `peter`、`denise` 或 `mark` 中随机选择一个文件夹。如果我选择 `peter`,它必须从 `peter_folder1`、`peter_folder2`、`peter_folder3` 的列表中随机选择一个文件夹。如果选择 `denise`,则从 `denise_folder1`、`denise_folder2` 等中选择。
到目前为止,我只筛选出文件夹并返回一个列表:
```python
os.chdir(folder_path)
sorted_folders = filter(os.path.isdir, os.listdir(folder_path))
print(sorted_folders)
请注意,这只是代码的翻译部分,不包括其他内容。
<details>
<summary>英文:</summary>
I am trying to randomly select a folder inside a directory possibly using `random.choice()` (or any). But it is actually not that random. It has to filter first the folders (inside that directory) based on a condition or variable and then randomly select a folder from that list
Example:
list of folders inside the directory are:
`peter_folder1`, `peter_folder2`, `peter_folder3`, `denise_folder1`, `denise_folder2`, `mark_folder1`, `mark_folder2`
I want to randomly select a folder from `peter`, or from `denise`, or from `mark`. If I choose `peter`, it has to randomly select a folder from the list of `peter_folder1`, `peter_folder2`, `peter_folder3`. If from `denise`, `denise_folder1`, `denise_folder2` and etc.
So far, I have only filtered the folders to return a list
os.chdir(folder_path)
sorted_folders = filter(os.path.isdir, os.listdir(folder_path)
print(sorted_folders)
</details>
# 答案1
**得分**: 0
你只需要筛选`sorted_folders`中以所需名称开头的文件夹。然后,你可以简单地在结果列表上运行`random.choice()`。与使用另一个带有lambda的`filer()`调用并将结果转换为列表不同,我选择使用了一个列表理解,但两者都可以正常工作:
```python
os.chdir(folder_path)
sorted_folders = filter(os.path.isdir, os.listdir())
name = input('输入一个筛选名称:')
filtered = [folder for folder in sorted_folders if folder.startswith(name)]
random_folder = random.choice(filtered)
print(random_folder)
请注意,我已将代码中的'Enter a filter name: '
替换为'输入一个筛选名称:'
,以使其更具可读性。
英文:
All you need to do is filer sorted_folders
for ones start with the intended name. From there, you can then simply run random.choice()
on the resulting list. Rather than using another filer()
call with a lambda and then converting the result to a list, I chose to use a list comprehension, however, both work fine:
os.chdir(folder_path)
sorted_folders = filter(os.path.isdir, os.listdir())
name = input('Enter a filter name: ')
filtered = [folder for folder in sorted_folders if folder.startswith(name)]
random_folder = random.choice(filtered)
print(random_folder)
答案2
得分: 0
这是代码的翻译部分:
import random
sorted_folders = ["peter_folder1", "peter_folder2", "peter_folder3", "denise_folder1", "denise_folder2", "mark_folder1", "mark_folder2"]
names = list(set(folder.split("_")[0] for folder in sorted_folders))
name = random.choice(names)
folders = [folder for folder in sorted_folders if folder.startswith(name)]
folder = random.choice(folders)
print(folder)
请注意,我已经移除了HTML实体编码(")并将代码翻译成了中文字符。如果您需要进一步的帮助,请随时告诉我。
英文:
How is this:
import random
sorted_folders = ["peter_folder1", "peter_folder2", "peter_folder3", "denise_folder1", "denise_folder2", "mark_folder1", "mark_folder2"]
names = list(set(folder.split("_")[0] for folder in sorted_folders))
name = random.choice(names)
folders = [folder for folder in sorted_folders if folder.startswith(name)]
folder = random.choice(folders)
print(folder)
答案3
得分: 0
以下是翻译好的部分:
假设您有一个标准的命名约定,例如,通过下划线分隔的名称。
这部分代码随机选择一个名称,例如 peter、denise 或 mark,尽管这部分也可以手动选择。然后,它从该人员中随机选择一个文件夹。
$ cat filter.py
import os
from secrets import choice, randbelow
folder_path = '.'
os.chdir(folder_path)
sorted_folders = [name for name in os.listdir() if os.path.isdir(name) \
and '_' in name]
print(sorted_folders)
choices = {name.split('_')[0]:[] for name in sorted_folders}
print(choices)
for name in sorted_folders:
choices[name.split('_')[0]].append(name)
print(choices)
while len(choices) > 0:
name = choice(list(choices.keys()))
choiceindex = randbelow(len(choices[name]))
folder = choices[name][choiceindex]
del choices[name][choiceindex]
if len(choices[name]) == 0:
del choices[name]
print(f'Chose {folder}')
给出的输出:
$ python filter.py
['peter_folder1', 'denise_folder2', 'peter_folder3', 'mark_folder1', 'mark_folder2', 'denise_folder1', 'peter_folder2']
{'peter': [], 'denise': [], 'mark': []}
{'peter': ['peter_folder1', 'peter_folder3', 'peter_folder2'], 'denise': ['denise_folder2', 'denise_folder1'], 'mark': ['mark_folder1', 'mark_folder2']}
Chose denise_folder2
Chose peter_folder3
Chose denise_folder1
Chose mark_folder2
Chose mark_folder1
Chose peter_folder2
Chose peter_folder1
英文:
Assuming you have a standard naming convention, e.g., name separated by an underscore.
This randomly selects a name, peter, denise, or mark, though that part could also be manual. Then it randomly selects a folder from that person.
$ cat filter.py
import os
from secrets import choice, randbelow
folder_path='.'
os.chdir(folder_path)
sorted_folders = [name for name in os.listdir() if os.path.isdir(name) \
and '_' in name]
print(sorted_folders)
choices = {name.split('_')[0]:[] for name in sorted_folders}
print(choices)
for name in sorted_folders:
choices[name.split('_')[0]].append(name)
print(choices)
while len(choices) > 0:
name = choice(list(choices.keys()))
choiceindex = randbelow(len(choices[name]))
folder = choices[name][choiceindex]
del choices[name][choiceindex]
if len(choices[name]) == 0:
del choices[name]
print(f'Chose {folder}')
Gives the output:
$ python filter.py
['peter_folder1', 'denise_folder2', 'peter_folder3', 'mark_folder1', 'mark_folder2', 'denise_folder1', 'peter_folder2']
{'peter': [], 'denise': [], 'mark': []}
{'peter': ['peter_folder1', 'peter_folder3', 'peter_folder2'], 'denise': ['denise_folder2', 'denise_folder1'], 'mark': ['mark_folder1', 'mark_folder2']}
Chose denise_folder2
Chose peter_folder3
Chose denise_folder1
Chose mark_folder2
Chose mark_folder1
Chose peter_folder2
Chose peter_folder1
答案4
得分: 0
When dealing with files in Python, a good alternative is to use pathlib
. If you're using Python 3.11, your entire example becomes:
from pathlib import Path
import random
folder = Path(folder_path)
sorted_folders = list(folder.glob("peter*")) # 选择以 "peter" 开头的所有文件夹...
random_folder = random.choice(sorted_folders)
Just remember that now you're dealing with Path
objects instead of strings.
type(random_folder) # PosixPath 或 WindowsPath
str(random_folder) # peter_folder2
英文:
When dealing with files in Python, a good alternative is to use pathlib
. If you're using python 3.11, your entire example becomes:
from pathlib import Path
import random
folder = Path(folder_path)
sorted_folders = list(folder.glob("peter*/")) # Select all folders that start with peter...
random_folder = random.choice(sorted_folders)
Just remember that now you're dealing with Path
objects instead of strings.
type(random_folder) # PosixPath or WindowsPath
str(random_folder) # peter_folder2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论