简体   繁体   English

我怎样才能遍历元组列表中的元素并将结果作为字符串获取?

[英]How could I iterate over the elements of a list of tuples and get the elements as strings as a result?

I'm just trying to write a program which loads a workbook, iterates over the values of all the cells in two columns, format a string with the values read from those cells and writes the resulting formatted string to a new worksheet's column's cells. 我只是在尝试编写一个程序,该程序加载工作簿,遍历两列中所有单元格的值,使用从这些单元格读取的值格式化字符串,并将生成的格式化字符串写入新工作表的列单元格。 My problem is that I cannot get the original values as strings to be able to format them with string operations. 我的问题是我无法获取原始值作为字符串,从而无法使用字符串操作格式化它们。 The other problem is that if I could even format the string successfully, I also don't know how to write the resulting string values to the new worksheet's column A. 另一个问题是,如果我什至可以成功格式化字符串,我也不知道如何将结果字符串值写入新工作表的列A。

This only appends the last element of fiok to fiokstr as string. 这只会将fiok的最后一个元素作为字符串附加到fiokstr中。 Any idea why only the last element is appended? 知道为什么只附加最后一个元素吗?

for x in fiok:
    fiokstr = []
    for y in x:
        fiokstr.append(y)

Move fiokstr outside the loop: fiokstr循环:

fiokstr = []
for x in fiok:
    for y in x:
        fiokstr.append(y)

As it is, you're reassigning an empty list to it for every run through the loop. 照原样,您要为循环中的每次运行重新分配一个空列表。

I might be reading this wrong, but it looks like every time it iterates through fiok , fiokstr gets set back to an empty list. 我可能读错了,但是看起来每次通过fiok迭代时, fiokstr都被设置回一个空列表。 Try defining fiokstr outside of that outer for loop. 尝试在外部for循环之外定义fiokstr Eg: 例如:

fiokstr = []
for x in fiok:
    newl = []
    for y in x:
        newl.append(y)
    fiokstr.append(newl)

Thank you all. 谢谢你们。 That populated fiokstr appropriately, along with another list, ipstr (same number of entries in the two lists). 那适当地填充了fiokstr和另一个列表ipstr(两个列表中的条目数相同)。

And why is the following? 为什么是以下内容?

When I run: 当我跑步时:

txt = [] txt = []

for nev in fiokstr:
    text = "H_"+nev.capitalize()
    txt.append(text)

or 要么

for cim in ipsrtr:
    text = "_UPS_"+cim.replace("/24", "")
    txt.append(text)

txt gets populated appropriately, but when I run: txt被适当填充,但是当我运行时:

for nev in fiokstr, cim in ipstr:

    text = "H_"+nev.capitalize()+"_UPS_"+cim.replace("/24", "")
    txt.append(text)

I get "NameError: name 'nev' is not defined", although previously worked as I wrote. 我收到“ NameError:未定义名称'nev'”的信息,尽管以前按我撰写的方式工作过。

Thank you. 谢谢。

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

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