将新字符串插入列表,并保存信息

时间:2018-08-28 09:49:24

标签: python

我正在学习Python,我想知道您如何将名称插入列表中并保留在该变量中,以便脚本可以识别以前是否见过您。

任何帮助将不胜感激

# Default People Already In List at program start
list = ['Bob','Jim',]
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in list:
    print("Nice to meet you again" + Name)
else:
    list.insert(0, Name)
    print("Hi " + Name + ", Nice too meet you for the first time.")

# Troubleshoot
print(list)

3 个答案:

答案 0 :(得分:1)

您应该重命名您的变量-尽管看起来已经不错了,但是这里是对代码的简短更正!我也将插入内容更改为追加!

但是显然,它会忘记,因为列表总是在其中包含Bob和Jim的情况下初始化的,然后您要求输入名称-如果不是Bob或Jim,则该名称是新的,因此要追加。但是程序结束了,所以当您重新启动它时,列表只再次填充了Bob&Jim。您可以将整个结构放入“ while True”结构中,以多次提出相同的问题,直到您不再想要!

EDIT:包括一会儿(如果您只是按“ Enter”输入问题,您可以输入多次!并将列表放在开头,因此不会在每次运行新名称时都进行初始化!) :如果您是第一次见到某人,请将其打印在else子句中,否则即使您之前看到过姓名,也将每次都打印该打印件!

name_list = ['Bob','Jim']
while True:

    print("Hello, What\'s your name? ")
    input_name = input("Enter your Name: ")
    if str(input_name) in name_list:
        print("Nice to meet you again, " + input_name)
    else:
        name_list.append(input_name)
        print("Hi " + input_name + ", Nice too meet you for the first time.")

    # Troubleshoot
    print(name_list)

    if str(input("Another name? ")) == '':
        continue
    else:
        break

答案 1 :(得分:1)

这就是我所做的。这适用于CSV文件。

public class PageTwo extends WizardPage {
    private Text text1;
    private Composite container;
    private Text text2;
    PageOne pageOne;
    DataTransferObject dto; 

    public PageTwo(DataTransferObject dto) {
        super("PageTwo ");
        this.dto=dto;
        setTitle("PageTwo ");
        setDescription("Fake Wizard: PageTwo");
    }

    public void setText(Text text){
        this.text2=text;
    }

    @Override
    public void createControl(Composite parent) {
        container = new Composite(parent, SWT.NONE);
        GridLayout layout = new GridLayout();
        container.setLayout(layout);
        layout.numColumns = 2;
       // Label label1 = new Label(container, SWT.NONE);
        String result="";

        org.eclipse.swt.widgets.List single = new org.eclipse.swt.widgets.List(container, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL);
        if(!(dto.data==null)){
            single.add(dto.getData());
        }
        setControl(container);
        setPageComplete(true);
    }

    public String getText1() {
        return text1.getText();
    }
}

答案 2 :(得分:0)

这会将其存储到文件中,将内置函数和实用程序用作变量名也不是一个好习惯。所以我将名称修改为列表

try:
    with open("listofnames.txt","r") as fd:
        lists=eval(fd.read())
except:
    lists=[['Bob','Jim',]]

print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in lists:
    print("Nice to meet you again", Name)
else:
    lists.insert(0, Name)
    with open("listofnames.txt","w") as f:
        f.write(str(lists))

    print("Hi " + Name + ", Nice too meet you for the first time.")

# Troubleshoot
print(lists)