简体   繁体   English

有没有办法遍历一个列表,并分配一个变量

[英]Is there a way to loop through a list, and assign a variable

What I'd like to do is assign variable (a) to each instance of (b).我想做的是将变量(a)分配给(b)的每个实例。 There are 30 folders within (a) It should look like the following: 'm:/groupfolder/susan/01' 'm:/groupfolder/susan/03' 'm:/groupfolder/susan/04'... (a) 中有 30 个文件夹 它应该如下所示: 'm:/groupfolder/susan/01' 'm:/groupfolder/susan/03' 'm:/groupfolder/susan/04'...

Here is what I'm doing -这就是我正在做的 -

import os
from os import listdir
a = ('m:/groupfolder/susan')
b = []
for x in os.listdir(a):
   b.append(x)

fha = [b]
for y in fha:
    path = a+b
 Error mesage = "TypeError: can only concatenate str (not "list") to str"

Please let me know what I'm doing wrong - yes I'm relatively new to Python and still learning.请让我知道我做错了什么 - 是的,我对 Python 还比较陌生,并且还在学习。 Thanks谢谢

Instead of collecting all filename in list and then iterating it again.而不是收集列表中的所有文件名然后再次迭代它。 You can simply do it in one step:您可以简单地一步完成:

import os                                                                                                                                                              

b = []                                                                                                                                                                 
for file in os.listdir(s): 
    print(file) 
    b.append(s+'/'+file) 

print(b) 

Use a list comprehension to get a list of full file paths:使用列表推导获取完整文件路径的列表:

import os
file_paths = [os.path.abspath(f) for f in os.listdir('dir_name')]
print(file_paths)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有办法遍历数据框并根据列表在新列中分配值? - Is there a way to loop through a dataframe and assign a value in a new column based on a list? 循环浏览一系列列表,执行一些操作并将其分配回列表的简短方法 - Short Way to Loop through a Series of List, Do Some Actions and Assign it Back to the List 有没有更简单的方法来分配字典并循环更新? - Is there a simpler way to assign a dictionary and loop through to update? 如何重复遍历列表以分配值 - How to repeatedly loop through list to assign values 遍历列表并将值分配给Python中的变量 - Iterate through list and assign a value to the variable in Python 有没有办法使用此代码循环遍历列表? - Is there a way to loop through a list with this code? 有没有办法循环遍历python中的列表? - Is there a way to loop through a list in python? 有没有一种更Python化的方式可以遍历列表,然后让每个循环变量更新字典? - Is there a more Pythonic way to loop through a list and then have each loop variable update a dictionary? 有没有办法遍历 python 中的 for 循环中的列表? - Is there a way to loop through a list which is in a for loop in python? 如何遍历pandas数据帧,并有条件地将值分配给一行变量? - How to loop through pandas dataframe, and conditionally assign values to a row of a variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM