简体   繁体   English

在一行上打印对象属性

[英]Printing object attributes on one line

I've got a list called "location" with two class-created objects inside: 我有一个名为“位置”的列表,里面有两个类创建的对象:

location = [rat1,rat2]

I'd like to print an attribute of both rats on one line, while keeping the location list dynamic. 我想在保持位置列表动态的同时在一行上打印两只老鼠的属性。 I have this currently: 我目前有这个:

for i in range(0,len(location)):
    print((location[i].vname),sep=',')

This iterates through the lists items, and prints the "vname" attribute for every object in the list it sees. 这将遍历列表项,并为它看到的列表中的每个对象打印“ vname”属性。 Unfortunately this currently returns: 不幸的是,这当前返回:

Young Rat
Adult Rat

If I change sep to end, it prints this: 如果我将sep更改为end,它将输出以下内容:

Young Rat,Adult Rat,

It's almost as if the sep isn't even registered at all in the print. 几乎好像Sep在印刷版中甚至都没有注册。 Does anyone have any ideas? 有人有什么想法吗? Also, sorry for any formatting issues, this is my first time posting on stack exchange. 另外,对于任何格式问题,对不起,这是我第一次在堆栈交换上发布。

You should make one call to print and join the various attributes using str.join . 您应该调用一次以使用str.join打印并加入各种属性。 The following should work: 以下应该工作:

print(','.join(rat.vname for rat in location))

Try print ','.join(location) or print ','.join(map(str, location)) 试试print ','.join(location)print ','.join(map(str, location))

More generally, don't iterate using an integer variable in python. 更一般而言,请勿在python中使用整数变量进行迭代。

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

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