看看下面的代码
testList = ["This", "Is", "A", "Test"]
dummyList = testList
dummyList = dummyList + ["Hello"]
Run Code Online (Sandbox Code Playgroud)
我期待更改testList的内容,因为dummyList引用testList,我们只是添加了一个新元素,但这没有发生.现在看下面的代码.
testList = ["This", "Is", "A", "Test"]
dummyList = testList
dummyList[0] = 'Hello'
Run Code Online (Sandbox Code Playgroud)
在此代码中,testList中发生了更改.为什么对dummyList的更改会改变第二块代码中testList的内容而不是第一块?
我有以下代码,称之为代码#1
Scanner keyboard = new Scanner(System.in);
String s = keyboard.nextLine();
int x = keyboard.nextInt();
double y = keyboard.nextDouble();
System.out.println("String: "+s);
System.out.println("Double: "+y);
System.out.println("Int: "+x);
Run Code Online (Sandbox Code Playgroud)
如果我输入
Hello World
12.1
12
Run Code Online (Sandbox Code Playgroud)
输出将是
String: Hello World
Double: 12.1
Int: 12
Run Code Online (Sandbox Code Playgroud)
但是,如果我重新排列我的代码,请将其称为 code#2,如
Scanner keyboard = new Scanner(System.in);
int x = keyboard.nextInt();
double y = keyboard.nextDouble();
String s = keyboard.nextLine();
System.out.println("String: "+s);
System.out.println("Double: "+y);
System.out.println("Int: "+x);
Run Code Online (Sandbox Code Playgroud)
我输入
12
12.1
Run Code Online (Sandbox Code Playgroud)
编译器跳过字符串输入和输出
String:
Double: 12.1
Int: 12
Run Code Online (Sandbox Code Playgroud)
这对我来说很奇怪。我被告知编译器总是从上到下阅读。我想象编译器将 code#2 读取为
int x = keyboard.nextInt();
Run Code Online (Sandbox Code Playgroud)
首先等待用户输入一个整数,以便将其分配给 x。然后读 …
我有以下列表:
A = [['Computer Science', 'Gender- Male', 'Race Ethnicity- Hispanic', 'Race Ethnicity- White'],
['Computer Science', 'Gender- Female', 'Race Ethnicity- White'],
['History', 'Gender-Female', 'Race Ethnicity- Black'],
['Mechanical Engineering', 'Geder- Male', 'Race Ethnicity- American Indian or Alaskan Native', 'Race Ethnicity- Hispanic']]
Run Code Online (Sandbox Code Playgroud)
我只想保留涉及种族和民族的元素.这就是我想要的结果:
B = [['Race Ethnicity- Hispanic', 'Race Ethnicity- White'],
['Race Ethnicity- White'],
['Race Ethnicity- Black'],
['Race Ethnicity- American Indian or Alaskan Native', 'Race Ethnicity- Hispanic']]
Run Code Online (Sandbox Code Playgroud)
以下类型的工作但不保留列表结构列表
[y for x in test for y in x if "Race Ethnicity" in y]
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?