0

I have 2 lists and an output file sent to a function I am having an issue with how to do the .write statement.

I have tried using an index, but get list error.

nameList = ['james','billy','kathy']
incomeList = [40000,50000,60000]

I need to search the lists and write the name and income to a file.

  for income in incomeList:
      if income > 40000:
          output.write(str("%10d    %12.2f \n")  # (this is what I can't figure out)))
7
  • Where are the names in your example code, don't they matter? What is you cannot figure out? What format do the lines need to be in? Commented Nov 23, 2020 at 5:05
  • What you want to write Commented Nov 23, 2020 at 5:07
  • In plain English, what do you think are the steps required to create the desired output line? Commented Nov 23, 2020 at 5:20
  • @Shadowcodder I am trying to get the second half of the .write statement...everything I have tried has errored. Commented Nov 23, 2020 at 5:20
  • please post an output of of how the file should look Commented Nov 23, 2020 at 5:21

3 Answers 3

1

You can do it like this.

nameList = ['james','billy','kathy']
incomeList = [40000,50000,60000]
for k, v in zip(nameList, incomeList):
    if v > 40000:
        print(k,v )

Output :-

 billy 50000
 kathy 60000
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that worked and explained zip function...yes I am just learning to program python.
1

Maybe this is what you want:

for i,income in enumerate(incomeList):
      if income > 40000:
          output.write(str(nameList[i]) )

Comments

0

In the case of 2 lists, I would suggest using a dict.

nameIncomeList = {'james':40000,'billy':50000,'kathy':60000}

For multiple case scenario,

f=open('f1.txt','w')
for i in range(len(nameList)):
    if incomeList[i]>40000:
        f.write(nameList[i]+' '+incomeList[i]+'\n')

f.close()

2 Comments

thank you , but I was given the lists and can't recombine them
Then the second solution will help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.