Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么我不';无法在一个索引中获取字符串?_Python_List_Python 3.x - Fatal编程技术网

Python 为什么我不';无法在一个索引中获取字符串?

Python 为什么我不';无法在一个索引中获取字符串?,python,list,python-3.x,Python,List,Python 3.x,当我尝试向数组插入字符串时,我得到的是['.','p','y']而不是[.py]: from os import walk Typofiles=[] t="" Ex="" f = [] for (dirpath, dirnames, filenames) in walk('D:\Python_Scripts'): f.extend(filenames) for i in range(1): t = f[i] indexO=t.rindex('.') LenF=le

当我尝试向数组插入字符串时,我得到的是
['.','p','y']
而不是
[.py]

from os import walk
Typofiles=[]
t=""
Ex=""
f = []
for (dirpath, dirnames, filenames) in walk('D:\Python_Scripts'):
    f.extend(filenames)
for i in range(1):
    t = f[i]
    indexO=t.rindex('.')
    LenF=len(t)
    Ex=(t[-(LenF-indexO):])
    if Ex in Typofiles:
        pass
    else:
        Typofiles.extend(Ex)

print (Typofiles)
print(Ex)

结果是:
['.','p','y']
如何获取
['.py']

之所以会发生这种情况,是因为
键入文件
是一个列表,您正在使用
.extend
方法。list的
.extend
方法接受一个iterable,并将iterable的每个元素附加到它自己。因此,它看起来像这样:

class List:
    def extend(self, iterable):
        for elem in iterable:
            self.append(elem)
因为
Ex
是一个字符串,所以它是一个iterable,因此要经过上述过程。相反,您要做的是使用
.append
方法,该方法只需将元素添加到列表中,不管元素是什么:

In [19]: L = []

In [20]: L.extend('.py')

In [21]: L
Out[21]: ['.', 'p', 'y']

In [22]: L = []

In [23]: L.append('.py')

In [24]: L
Out[24]: ['.py']

这是因为
Typofiles
是一个列表,并且您正在使用
.extend
方法。list的
.extend
方法接受一个iterable,并将iterable的每个元素附加到它自己。因此,它看起来像这样:

class List:
    def extend(self, iterable):
        for elem in iterable:
            self.append(elem)
因为
Ex
是一个字符串,所以它是一个iterable,因此要经过上述过程。相反,您要做的是使用
.append
方法,该方法只需将元素添加到列表中,不管元素是什么:

In [19]: L = []

In [20]: L.extend('.py')

In [21]: L
Out[21]: ['.', 'p', 'y']

In [22]: L = []

In [23]: L.append('.py')

In [24]: L
Out[24]: ['.py']

因为
extend
ing一个列表会导致iterable参数中的每个元素都被单独追加:

L.extend(iterable)->None
--通过追加iterable中的元素来扩展列表

您正在查找
.append
,它获取对象并将其简单地放在列表的末尾:

l = []    
l.append(".py")
print(l)  # ['.py'] 

因为
extend
ing一个列表会导致iterable参数中的每个元素都被单独追加:

L.extend(iterable)->None
--通过追加iterable中的元素来扩展列表

您正在查找
.append
,它获取对象并将其简单地放在列表的末尾:

l = []    
l.append(".py")
print(l)  # ['.py']