简体   繁体   English

using.remove() 从列表中删除字符串的问题?

[英]Issue with using .remove() to take strings away from lists?

I have a big list of companies that I'm iterating through and I want the program to get rid of the individual company that I go through in the for loop.我有一长串要遍历的公司,我希望程序摆脱我 go 在 for 循环中通过的个别公司。 The issue is that I print the companies list each time in the for loop and it always prints the same list even after I do.remove().问题是我每次都在 for 循环中打印公司列表,即使在我执行 do.remove() 之后它也总是打印相同的列表。

Code:代码:

for company in companies:
    test_times = test_times + 1
    companies.remove(company)
    print(f'Companies list: {companies}')
    print(f'Dictionary: {companies_sector}')

Example of output of printing companies:印刷公司output示例:

['AA', 'AAAGY', 'AABC', 'AACB', 'AACE', 'AACPF', 'AAI1', 'AAIIQ', 'AAL', 'AAME', 'AANB', 'AAON']

Example of second output where company 'AA' should have been removed:第二个 output 的示例,其中公司“AA”应该已被删除:

['AA', 'AAAGY', 'AABC', 'AACB', 'AACE', 'AACPF', 'AAI1', 'AAIIQ', 'AAL', 'AAME', 'AANB', 'AAON']

Not sure what to do.不知道该怎么办。

Part of your problem is that you are iterating over a list that keeps changing.您的部分问题是您正在迭代一个不断变化的列表。 Try it this way.试试这个方法。

companies =  ['AA', 'AAAGY', 'AABC', 'AACB', 'AACE', 'AACPF', 'AAI1', 'AAIIQ', 'AAL', 'AAME', 'AANB', 'AAON']
companies_list =  companies [:]
for company in companies:
    companies_list.remove(company)
    print(f'Companies list: {companies_list}')

Edit: In response to a question from the original poster in the comments, please run the code below and study the output. I think that will explain it better than I can.编辑:针对评论中原始发布者的问题,请运行以下代码并研究 output。我认为这会比我更好地解释它。

array = ['a', 'b', 'c', 'd', 'e', 'f']
for element in array :
    print (f'\nThe element about to be removed is "{element}".')
    print (f'It is at location {array.index (element)} in the array.')
    print (f'The array is now {array}.')
    input ('Press enter to continue.')
    array.remove (element)

print (f'\nThe array ended up {array}.')

You could iterate the list, and get a subset of the list, but the first element:您可以迭代列表,并获取列表的子集,但第一个元素:

for _ in range(len(companies)):
  element = companies[0]
  print(f'element: {element}')
  companies = companies[1:]
  print(f'companies: {companies}')

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM