2016-07-14 77 views
0

我试图通过列表循环以找到匹配除最后一个字符以外的文件名,并将匹配串接成一个字符串。Python循环遍历匹配字符串的长列表并连接

我遇到的困难是每个文件名有不同的匹配数量,所以可能有一个文件没有匹配,一个文件有两个匹配,三个或四个。

我正在使用'skip'变量来尝试并通过迭代已经匹配的循环来避免重复。

我认为问题来自于我使用'i'变量从列表中获取元素,但我不确定。

正如你或许可以告诉我是新来的Python和编程,并有一个严重的缺陷,在我的逻辑,我看不到!如果有什么不清楚的地方,我会尽我所能解释,任何帮助将不胜感激。

reader = [34113751IHF.jpg, 34113751IHR.jpg, 34136676OTD.jpg, 34136676OTF.jpg, jpg34136676OTR.jpg, 34136676OTF.jpg, 34136676OTR.jpg, 34139933EDD.jpg, 34139933EDF.jpg, 34144626KXF.jpg, 34144626KXR.jpg] 

iterable = iter(reader) 

skip = 0 

for i, j in enumerate(iterable): 

    firstURL = str(j)[2:-2] 
    firstShorter = str(reader[i+1])[2:-3] 
    secondURL = str(reader[i+1])[2:-2] 
    secondShorter = str(reader[i+1])[2:-3] 

    if firstShorter == secondShorter: 
     toWrite = firstURL + ".jpg|" + secondURL + ".jpg" 
     thirdURL = str(reader[i+2])[2:-2] 
     thirdShorter = str(reader[i+2])[2:-3] 
     skip = 2 

     if secondShorter == thirdShorter: 
      toWrite += "|" + thirdURL + ".jpg" 
      fourthURL = str(reader[i+3])[2:-2] 
      fourthShorter = str(reader[i+3])[2:-3] 
      skip = 3 

      if thirdShorter == fourthShorter: 
       toWrite += "|" + thirdURL + ".jpg" 
       fifthURL = str(reader[i+4])[2:-2] 
       fifthShorter = str(reader[i+4])[2:-3] 
       skip = 4 

    else: 
     toWrite = firstURL + ".jpg" 
     skip = 1 

    [iterable.__next__() for x in range(skip)] 
+0

你能写出你期望的输出吗?很难理解你的问题。你想要一个像这样的列表:[“34113751IHF34113751IHR”,“34136676OTD34136676OTF”,...]? –

回答

2

如果我正确理解你想要的一组匹配(除了最后一个字符名为.jpg)到一个字符串这是所有的文件名串连所有文件名?下面是一个示例:

from collections import Counter 

# The list you provided 
reader = ['34113751IHF.jpg', '34113751IHR.jpg', '34136676OTD.jpg', '34136676OTF.jpg', '34136676OTR.jpg', 
      '34136676OTF.jpg', '34136676OTR.jpg', '34139933EDD.jpg', '34139933EDF.jpg', '34144626KXF.jpg', 
      '34144626KXR.jpg'] 

# Creating a copy of the list but without the last character and '.jpg' 
check_list = [x[:-5] for x in reader] 

counter = Counter(check_list) 
grouped_list = [[k]*v for k, v in counter.items()] 

这将创建一个符合条件的所有文件名的列表。如果你想要列表的字符串表示,你可以这样做:

string_rep = " | ".join(["".join(element) for element in grouped_list]) 
print(string_rep) 
OUTPUT: 34113751IH34113751IH | 34144626KX34144626KX | 34139933ED34139933ED | 34136676OT34136676OT34136676OT34136676OT34136676OT 
+0

感谢您的帮助!我救了我几个小时的挠头! –