简体   繁体   English

python嵌套循环列表

[英]python nested loop list

I am currently stuck at one nested loop problem.我目前被困在一个嵌套循环问题上。 I would appreciate it greatly if anyone can offer their insight or tips on how to solve this sticky problem that i am facing.如果有人可以提供有关如何解决我面临的这个棘手问题的见解或提示,我将不胜感激。

I am trying to append some values to a list in a for loop.我正在尝试将一些值附加到 for 循环中的列表中。 I succeeded in doing that.我成功地做到了这一点。 But how can I get the last list as my variable to use in another loop?但是如何将最后一个列表作为我的变量用于另一个循环?

Lets say.说吧。 I am extracting something by appending them in a list in a for loop.我通过将它们附加到 for 循环的列表中来提取一些东西。

a=list()
for b in hugo:
    a.append(ids)
    print(a)

gives me给我

[1]
[1,2]
[1,2,3]
[1,2,3,4]

But I only need the last line of the list as my variable to be used in another for loop.但我只需要列表的最后一行作为在另一个 for 循环中使用的变量。 Can anybody gives me some insights how to do this?任何人都可以给我一些如何做到这一点的见解吗? Your help is much appreciated.非常感谢您的帮助。 Thanks in advance.提前致谢。

Edit:编辑:

Actually I am not trying to get someone to do my homework for me.其实我并不是想找人帮我做作业。 I am just testing some software programming using python.我只是在使用 python 测试一些软件编程。 Here goes:开始:

I am trying to write a script to extract files with the end name of .dat from ANSA pre-processor with the correct name and file ID我正在尝试编写一个脚本,以从具有正确名称和文件 ID 的 ANSA 预处理器中提取结尾名称为 .dat 的文件

For example:例如:

ID       Name
1        hugo1.dat
8        hugo2.dat
11       hugo3.dat
18       hugo4.dat

Here is what I have written:这是我写的:

import os
import ansa
from ansa import base
from ansa import constants
from ansa import guitk

def export_include_content():
  directory = gutik.UserInput('Please enter the directory to Output dat files:')
  ishow=list()
  includes=list()
  setna=list()
  iname=list()

# Set includes variables to collect the elements from a function known as "INCLUDE" from the software
includes=base.CollectEntitites(deck, None, "INCLUDE")

# For loop to get information from the "INCLUDE" function with the end filename ".dat"
for include in includes:
    ret=base.GetEntityCardValues(deck, include, 'NAME', 'ID')
    ids=str(ret['ID'])
    setname=ret['NAME']
    if setname.endswith('dat'):
        ishow.append(ids)
        iname.append(setname)

# Print(ishow) gives me
[1]
[1,8]
[1,8,11]
[1,8,11,18]

# print(iname) gives me
[hugo1]
[hugo1,hugo2]
[hugo1,hugo2,hugo3]
[hugo1,hugo2,hugo3,hugo4]

# Now that I got both of my required list of IDs and Names. It's time for me to save the files with the respective IDs and Names.

for a in ishow:
        test=base.GetEntity(deck,'INCLUDE',int(a))
        print(a)
        file_path_name=directory+"/"+iname
        print(file_path_name)

#print(a) gives me
1
8
11
18

#print(file_path_name) gives me
filepath/[hugo1,hugo2,hugo3,hugo4]
filepath/[hugo1,hugo2,hugo3,hugo4]
filepath/[hugo1,hugo2,hugo3,hugo4]
filepath/[hugo1,hugo2,hugo3,hugo4]

# This is the part I got stuck. I wanted the output to be printed in this order:

1
filepath/hugo1

8
filepath/hugo2

11
filepath/hugo3

18
filepath/hugo4

But it doesnt work well so far for me, that's why I am asking whether you all can provide me some assistance on solving this problem :) Helps appreciated!!但到目前为止它对我来说效果不佳,这就是为什么我问你们是否可以为我提供解决这个问题的一些帮助:) 帮助表示赞赏! Thanks all谢谢大家

Your problem is with the code indent:您的问题在于代码缩进:

a=list()
for b in hugo:
    a.append(ids)
print(a)

Use a dictionary instead of having 2 separate list for ids and names of includes The code below creates a dictionary with include id as keys and the corresponding include's name as the value.使用字典而不是包含 id 和名称的 2 个单独列表 下面的代码创建一个字典,其中包含 id 作为键,相应的包含名称作为值。 later this dict is used to print file name后来这个字典用于打印文件名

In case you want to save each include as separate file,First isolate the include using "Or"(API) then we have an API for each deck in ANSA to do save files(make sure to enable optional argument 'save visible').for example for NASTRAN it is OutputNastran you can search it in the API search tab in the script editor window如果您想将每个包含保存为单独的文件,首先使用“或”(API)隔离包含,然后我们在 ANSA 中为每个卡组提供一个 API 来保存文件(确保启用可选参数“保存可见”)。例如,对于 NASTRAN,它是 OutputNastran,您可以在脚本编辑器窗口的 API 搜索选项卡中搜索它

dict={}
for include in includes:
    ret=base.GetEntityCardValues(deck, include, 'NAME', 'ID')
    ids=str(ret['ID'])
    setname=ret['NAME']
    if setname.endswith('.dat'):
        dict[ids]=setname
for k, v in dict.items():
   test=base.GetEntity(deck,'INCLUDE',int(k))
   file_path_name=directory+"/"+v
   print(file_path_name)

Hope this helps希望这可以帮助

Your current code has the loop printing every single time it iterates through, so move the print statement left to the same indent level as the for loop, so it only prints once the for loop has finished running its iterations.您当前的代码在每次迭代时都会打印循环,因此将打印语句向左移动到与 for 循环相同的缩进级别,这样它只会在 for 循环完成其迭代后才打印。

a=list()
for b in hugo:
    a.append(ids)
print(a)

Assuming ids is actually just the elements in hugo:假设 ids 实际上只是 Hugo 中的元素:

a=[id for id in hugo]
print(a)

Or或者

a=hugo.copy()
print(a)

Or或者

print(hugo)

Or或者

a=hugo
print(a)

Or或者

string = "["
for elem in hugo:
  string.append(elem + ",")
print(string[:-1] + "]")

Edit: Added more amazing answers.编辑:添加了更多惊人的答案。 The last is my personal favourite.最后一个是我个人的最爱。

Edit 2:编辑2:

Answer for your edited question:回答您编辑的问题:

This part这部分

for a in ishow:
    test=base.GetEntity(deck,'INCLUDE',int(a))
    print(a)
    file_path_name=directory+"/"+iname
    print(file_path_name)

Needs to be changed to需要改为

for i in range(len(ishow)):
    test=base.GetEntity(deck,'INCLUDE',int(ishow[i]))
    file_path_name=directory+"/"+iname[i]

The print statements can be left if you wish.如果您愿意,可以保留打印语句。

When you are trying to refer to the same index in multiple lists, it is better to use for i in range(len(a)) so that you can access the same index in both.当您尝试在多个列表中引用相同的索引时,最好使用for i in range(len(a))以便您可以访问两个列表中的相同索引。

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

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