-2

I am having a problem accessing multiple lists with two criteria: Case_Num and Case_Type. I do not know how to fix the error of concatenate string and lists objects.

I have tried using loops and combing strings and regular integer values.Unfortunatley I keep getting same error. Any help would be appreicated

_2019_case_1=[]

_2019_case_2=[]

_2019_case_3=[]


Case_Num=[2019,2019,2019,2020,2020,2020,2024,2024,2024,2029,2029,2029]
Case_Type=[1,2,3,1,2,3,1,2,3,1,2,3]

dr = "F:\C\FE\CD\Tran\ctg"
read_files =[] 
for root, _, files in os.walk(dr):
    read_files_2="_"+Case_Num+"_case_"+Case_Type 
    for file in files:
        if file in read_files_2:
            read_files.append(os.path.join(root, file))

Error I receive

read_files_2="_"+Case_Num+"_case_"+Case_Type
TypeError: cannot concatenate 'str' and 'list' objects
joe
  • 53
  • 9

1 Answers1

2

You need to change the line where you assign read_files_2 to a set comprehension. And best to just do this once so assign it before the loops. As stated in the comments you can use itertools.product as well for easily extensible changes.

from itertools import product

_2019_case_1=[]

_2019_case_2=[]

_2019_case_3=[]

dr = "F:\C\FE\CD\Tran\ctg"
read_files =[] 
read_files_2= {f"_{num}_case_{type}" for num, type in product((2019,2020,2024,2029), (1,2,3))}
for root, _, files in os.walk(dr): 
    for file in files:
        if file in read_files_2:
            read_files.append(os.path.join(root, file))
Jab
  • 26,853
  • 21
  • 75
  • 114
  • you could use `itertools.product` on `[2019,2020,2024,2029]` and `[1,2,3]` to make it a little shorter and readable (and easily extensible to more nums and types) – Adam.Er8 Jul 09 '19 at 13:46
  • `{f"_{num}_case_{type}" for num, type in product((2019,2020,2024,2029), (1,2,3))}` I get a syntax error with the quotation marks @Jab – joe Jul 09 '19 at 15:05
  • i do not have Python 3.6 – joe Jul 09 '19 at 15:14
  • Just use the string concatenation like in your question or str.format – Jab Jul 09 '19 at 15:26
  • `read_files_2={"_{num}_case_{type}".format(num, type)for num, type in product((2019,2020,2024,2029), (1,2,3))}` I tried this but i get a `KeyError: 'num'` – joe Jul 09 '19 at 15:39